ios - 尝试使用 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 分离
你能帮我解决这个问题吗?
解决方案
推荐阅读
- sas - 两组SAS产品
- ansible - Ansible:有条件地打破重试循环
- java - 如何在 Java 中暂停和恢复计时器
- python - pandas to_sql() 错误 - 对于准备好的语句,超出了每个会话 20 MB 的内存限制
- javascript - 如何将浏览器滚动位置从垂直更改为水平
- prometheus-alertmanager - 在 Prometheus 中拉而不是推动警报升级
- python - matplotlib 财务自定义 y/x 轴
- python - 删除文件中的所有行,直到与字符串一致
- reactjs - 如何使用 react app 在 index.scss 文件中添加 normalize.css
- javascript - 如何在 React 中创建组件的 props.children 元素的索引数组