首页 > 解决方案 > 尝试使用 App Groups 和 UserDefaults 在 Apple Watch 和 iOS 应用程序之间同步数据

问题描述

我想创建一个与手表应用程序同步(并共享一些数据)的简单 iOS 应用程序。我尝试使用 AppGroup 和 UserDefaults 来做到这一点。iOS 应用程序保存数据,但 Apple Watch 应用程序无法读取数据。有谁知道原因?可能是因为我的免费开发帐户?

iOS 代码:

    @IBAction func buttonPressed(_ sender: Any) {
    print(FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my.app")!
    .appendingPathComponent("switchState.plist"))

    var sharedDefault = UserDefaults(suiteName: "group.com.my.app")

         sharedDefault?.set(textFieldOne.text, forKey: "shared1")
         print(UserDefaults(suiteName: "group.com.my.app")!.string(forKey: "shared1")!)
         sharedDefault?.synchronize()
}

iWatch 代码:

@IBAction func buttonPressed() { 
let sharedDefault = UserDefaults(suiteName: "group.com.my.app")
     print(FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my.app")!
     .appendingPathComponent("switchState.plist"))
     print(UserDefaults(suiteName: "group.com.my.app")?.object(forKey: "shared1"))
     let sharedText = sharedDefault!.string(forKey: "shared1")
     textField.setText(sharedText)
     print(sharedText)

}

当我运行 iOS 应用程序时 - 它会向 switchState.plist 写入路径中具有值的键:/Users/_userName/Library/Developer/CoreSimulator/Devices/F5A0485A-CBB7-4903-8339-738DBE3491B6/data/Containers/Shared/AppGroup /5C371E82-27A7-4BB3-982D-B0E5CDE5AC52/Library/Preferences/switchState.plist

但是当我尝试在 iWatch 应用程序中读取该数据时 -

/Users/_userName/Library/Developer/CoreSimulator/Devices/6F195AF7-73CA-4AF9-8CFE-5B47286F3DE5/data/Containers/Shared/AppGroup/533FEFB3-4A77-4A2B-8A53-99CF916D5481/

没有 plist 文件(当然返回 nil)!

但!当我在第二条路径中手动添加 Library/Preferences/switchState.plist 时 - 它工作得很好!

我已经在真实设备上尝试过这个 - iWatch 应用程序说:

file:///private/var/mobile/Containers/Shared/AppGroup/D297CDB8-F623-4BDF-83D8-15505451EC92/switchState.plist 2020-03-04 10:59:25.736335+0200 IosWatchOsTest 扩展[288:94115] [用户默认值] 无法读取 CFPrefsPlistSource<0x16d92960> 中的值(域:group.com.sk.todoey-ios13.Todoey,用户:kCFPreferencesAnyUser,ByHost:是,容器:(null),需要刷新的内容:是):使用带有容器的 kCFPreferencesAnyUser 仅允许用于系统容器,与 cfprefsd 分离

你能帮我解决这个问题吗?

标签: iossynchronizationwatchios-app-group

解决方案


推荐阅读