是否仍然可以在 iOS 和 tvOS 之间共享 UserDefaults?
在我的 Xcode 项目中,我使用 UserDefaults
在我的 iOS 目标和我的 tvOS 目标之间共享数据。当我尝试从我的 tvOS 应用程序取回数据时,我总是从我的 UserDefaults
收到 nil 值。
这些是我共享数据所采取的步骤:
1:为两个目标添加应用组。两个目标使用相同的 App Group ID: group.nl.mycompany.myappname。
我使用 .nl 域,但这应该没问题,因为这也适用于我的其他项目。
2:确认两个目标具有相同的部署目标。 我尝试使用 10.0 和 11.0。
3:验证 myproject.entitlements 是否一切都已设置好。
4:验证在 developer.apple.com 上是否为我的包标识符启用了应用组。
5:两个目标具有相同的包 ID。我还尝试使用 2 个不同的包标识符。
6:我从我的 iOS 应用程序写入 UserDefaults
的方式:
guard let defaults = UserDefaults(suiteName: "group.nl.mycompany.myappname") else { return }
defaults.set("Apple", forKey: "username")
defaults.synchronize()
我通过获取如下值来确认这在我的 iOS 应用程序中有效:
guard let defaults = UserDefaults(suiteName: "group.nl.mycompany.myappname") else { return nil }
defaults.synchronize()
let name = defaults.string(forKey: "username")
这确实返回了“Apple”。
7:打开我的 tvOS 应用程序并调用此代码返回 nil:
guard let defaults = UserDefaults(suiteName: "group.nl.mycompany.myappname") else { return nil }
defaults.synchronize()
let name = defaults.string(forKey: "username")
是否有可能 UserDefaults
共享已被删除?在您的手机和 watch 链接之间共享 UserDefaults
时发生了类似的事情链接 here .我还读到 UserDefaults
的最大大小是 500kb对于 AppleTV,但保存这个简单的字符串应该没问题。
最佳答案
Apple 在 UserDefaults
中明确说明文档
With the exception of managed devices in educational institutions, a user’s defaults are stored locally on a single device, and persisted for backup and restore. To synchronize preferences and other data across a user’s connected devices, use
NSUbiquitousKeyValueStore
instead.
如其所说,您应该使用基于 iCloud 的 NSUbiquitousKeyValueStore
用于同步数据存储。
至于它的 (NSUbiquitousKeyValueStore
) 限制,文档说
The total amount of space available in your app’s key-value store, for a given user, is 1 MB. There is a per-key value size limit of 1 MB, and a maximum of 1024 keys.
关于ios - 是否仍然可以在 iOS 和 tvOS 之间共享 UserDefaults?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49651571/