しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

【Swift, App Group】アプリ間でデータを共有する

アプリ間でデータを共有できる、App Groupを試してみました。
UserDefaultsのデータとファイルが共有可能です。
ただし自分が開発したアプリ同士でないと共有できないので注意が必要です。

まずは下のように、アプリを2つ作成します。
最初にMyApp1でデータの保存をしてみます。

f:id:llcc:20170730224732p:plain

まずはApp Groupを作成します。
XcodeのCapabilitiesからAppGroupをONにします。

f:id:llcc:20170730225239p:plain

有効化したら新しいApp Groupを作成します。
+ボタンから、AppGroupを追加してください。

f:id:llcc:20170730225258p:plain

続けてデータ保存部分の実装をします。
データ保存は下のように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選択を行います。

f:id:llcc:20170730225916p:plain

取得は下の通りです。
無事に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()