【问题标题】:How can local settings be stored on apple watch?本地设置如何存储在 Apple Watch 上?
【发布时间】:2017-07-10 19:58:10
【问题描述】:

我知道here 列出的用于在 Apple Watch 和 iOS 上保存偏好设置的方法。

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

我正在寻找一种在手表本地存储偏好的方法。这些偏好仅适用于手表(因此共享偏好方案不是我想要的)。此外,该方法需要在有或没有电话的情况下工作。

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

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

编辑:我已经意识到,即使 Apple 不鼓励在手表上设置首选项,这也是完全可能的(可以像在 iOS 中一样使用 UserDefaults)。这使我可以进行本地手表设置。然后,如果需要在手机和手表之间传输设置,Watch Connectivity(特别是 TransferUserInfo)可以完成这项工作。

【问题讨论】:

    标签: swift nsuserdefaults apple-watch watchos wkinterfaceswitch


    【解决方案1】:

    UserDefaults 只是一个文件支持的字典。该文件存储为 plist,并且 UserDefaults 基本上构建在 PropertyListSerialization 之上。对于简单的设置,您可以滚动自己的默认值。手表上的文件存储和iOS基本一样:

    数据放置。 WatchKit 扩展必须在管理数据方面发挥积极作用。 WatchKit 扩展的容器目录与 iOS 应用程序的容器具有相同的基本结构。将用户数据和其他关键信息放在 Documents 目录中。尽可能将文件放在 Caches 目录中,以便在可用磁盘空间不足时被系统删除。

    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

    【讨论】:

    • 既然可以使用UserDefaults.standard,为什么还要这样做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多