ios - 设置包不适用于 watchOS 2

标签 ios nsuserdefaults watchkit ios-app-group

这在 watchOS 1 上不是问题,但现在在 watchOS 2 上我无法读取 watch 扩展上的值。

根据 Apple docs , 有可能的。 据一些人说 this thread , 有可能的。 据 Apple 员工称 this thread , 这是可能的。

据我所知,我正在正确设置所有内容:

  • 我在 iOS 应用和 watch 扩展上启用了应用组 相同的标识符。
  • 我将 Settings-Watch.bundle 添加到 iOS 应用 并添加了相同的 ApplicationGroupContainerIdentifier plist 的标识符

当我使用标识符作为套件名称初始化 NSUserDefaults 对象时,我无法读取 watch 扩展上的值。我可以在 iOS 应用程序上阅读它们。这发生在模拟器和真实设备中。

请不要发布有关如何使用 Watch Connectivity 执行此操作的答案。可以在没有 Watch Connectivity 的情况下仅使用 watchOS 2 上的共享应用程序组来执行此操作,人们能够做到这一点,这里直接来自 docs :

In watchOS 2, your WatchKit extension may read the values of preferences, but you cannot write new values. Preferences in watchOS 2 are forwarded from iOS to Apple Watch, but any modifications you make are not sent back to iOS.

最佳答案

我已经编辑了我的答案。之前,它谈到了无法使用 App Groups 在 watchOS 2 中同步数据,但你的具体问题是关于设置包,它仍然从 iOS 同步到 watchOS 2 中的 Apple Watch。

我无法在模拟器的 Xcode 7.1/7.2 中使用它,但它确实可以在真实设备上使用。来自文档:

Preferences in watchOS 2 are forwarded from iOS to Apple Watch, but any modifications you make are not sent back to iOS. In watchOS 1, WatchKit extensions have direct access to the defaults database and may read and write values.

所有 3 个目标都应配置相同的 App Group(此处的 Watch App 目标似乎是 OP 问题中缺少的组件):

targets app group

我的设置包:

enter image description here enter image description here

InterfaceController.swift中一些简单的接口(interface)代码:

@IBOutlet var label: WKInterfaceLabel!

@IBAction func buttonAction() {

    let sharedDefaults = NSUserDefaults.init(suiteName: "group.testSettings")
    let name_preference = String(sharedDefaults?.objectForKey("name_preference"))
    self.label.setText(name_preference)
}

和最终结果:

enter image description here enter image description here

因此,它确实按预期工作,只是在模拟器中没有。 Simulator 中的两个设备之间似乎存在一些隔离,试图准确了解那里发生的事情有点令人沮丧。

关于ios - 设置包不适用于 watchOS 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32638667/

相关文章:

ios - 确定用户是否已启用应用程序的 Safari 内容拦截器扩展

ios - iPhone - [NSUserDefaults standardUserDefaults] 文件存储在计算机上的什么位置?

cocoapods - 无法使用 cocoapods 在 watchKit 2.0 中加载动态库

Swift WatchOS 错误 : Unknown property in Interface description ('image' ) for controller

ios - 防止屏幕灯关闭 |在 watch 界面禁用 sleep 模式

ios - UICollectionView Objective-c 的长按点击手势识别器

ios - 带解析的 iMessage 扩展

ios - 我无法获取 Facebook 访问 token 来在 iOS 上使用图形 API

iphone - iOS SDK : Conjoined Text Fields

ios - 在 NSUserDefaults iOS 中保存 int 的问题