アプリ間でデータを共有できる、App Groupを試してみました。
UserDefaultsのデータとファイルが共有可能です。
ただし自分が開発したアプリ同士でないと共有できないので注意が必要です。
まずは下のように、アプリを2つ作成します。
最初にMyApp1でデータの保存をしてみます。
まずはApp Groupを作成します。
XcodeのCapabilitiesからAppGroupをONにします。
有効化したら新しいApp Groupを作成します。
+ボタンから、AppGroupを追加してください。
続けてデータ保存部分の実装をします。
データ保存は下のようにsuiteName付きでUserDefaultsを初期化して行います。
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let userDefaults = UserDefaults(suiteName: "group.com.myapp") userDefaults?.set(10, forKey: "testKey") userDefaults?.synchronize() print(userDefaults?.integer(forKey: "testKey")) // → 10 return true } }
MyApp1でデータを保存したので、次はMyApp2でそのデータを取得してみます。
MyApp2を起動したら、MyApp1のときと同様にCapabilitiesからAppGroup有効化と先ほど作成したApp Group選択を行います。
取得は下の通りです。
無事にMyApp1で保存したデータを取得できました。
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let userDefaults = UserDefaults(suiteName: "group.com.myapp") print(userDefaults?.integer(forKey: "testKey")) // → 10 return true } }
それとsuiteNameは、Typoしてもエラーになったりnilを返したりしないので気をつける必要があります。
let userDefaults = UserDefaults(suiteName: "group.com.myapp.wrong") userDefaults?.set(12, forKey: "testKey") userDefaults?.synchronize()