如何将本地设置存储在 Apple Watch 上?

How can local settings be stored on apple watch?

我知道 here 列出的方法可以在 Apple Watch 和 iOS 中保存偏好设置。

但是,他们提到无法在 Apple Watch 端更改设置,并且需要 WCSession 才能从手表更改设置。

我正在寻找一种在手表本地存储首选项的方法。这些首选项仅适用于手表(因此共享首选项方案不是我要找的)。此外,该方法需要在存在或不存在 phone 的情况下工作。

我的最终目标只是让我的 Apple Watch 应用程序上的开关在用户在手表上更改它们时保持其状态。如果应用程序关闭并重新打开,我希望保留它们的状态。

关于如何做到这一点有什么想法吗?到目前为止我唯一的想法是在手表本地保存一个文件并在启动时从中读取,但我觉得必须有更简单的方法。

编辑: 我后来意识到,尽管 Apple 不鼓励在手表上设置首选项,但这是完全可能的(UserDefaults 可以完全按照 iOS).这让我可以进行本地手表设置。然后,如果需要在 phone 和手表之间传输设置,Watch Connectivity(特别是 TransferUserInfo)可以完成这项工作。

UserDefaults 只是一个文件支持的字典。该文件存储为 plist,而 UserDefaults 基本上构建在 PropertyListSerialization 之上。对于简单的设置,您可以使用自己的默认设置。手表上的文件存储与iOS基本相同:

Data placement. WatchKit extensions must take an active role in managing your data. The container directory for your WatchKit extension has the same basic structure as the container for your iOS app. Place user data and other critical information in the Documents directory. Place files in the Caches directory whenever possible so that they can be deleted by the system when the amount of free disk space is low.

let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

guard let url = urls.first else {
    return
}

// The types that can be stored in this dictionary are the same as what NSUserDefaults can do
let preferences = [ "myDefault" : true ]

if let data = try? PropertyListSerialization.data(fromPropertyList: preferences, format: .xml, options: 1) {
    do {
        try data.write(to: url.appendingPathComponent("mypreferences.plist"))
    } catch {
        print("Failed to write")
    }
}

if let input = try? Data(contentsOf: url.appendingPathComponent("mypreferences.plist")),
    let dictionary = try? PropertyListSerialization.propertyList(from: input, options: .mutableContainersAndLeaves, format: nil),
    let d = dictionary as? [String : Bool],
    let value = d["myDefault"] {
        print(value)
}

或者

要共享首选项,您可以使用解决方案 here