【问题标题】:Sharing UserDefault between targets doesn't work在目标之间共享 UserDefault 不起作用
【发布时间】:2021-05-14 16:59:54
【问题描述】:

在目标之间共享 UserDefault 不起作用。我已经为这两个目标设置了应用组,但数据在 watchOS 上不可用。查看我的简化代码:

在 iOS 上:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let defaults = UserDefaults(suiteName: "group.my-bundle-id")!
    defaults.set(true, forKey: "testKey")

    return true
}

在 watchOS 上:

func applicationDidFinishLaunching() {
    let defaults = UserDefaults(suiteName: "group.my-bundle-id")!
    let uddata = defaults.bool(forKey: "testKey")
    print(uddata) // Still returns false
}

这是应用组(为 EACH 目标设置!):

【问题讨论】:

    标签: ios swift xcode watchos userdefaults


    【解决方案1】:

    根据this

    现代版本的 watchOS 在 Apple Watch 上运行您的 WatchKit 扩展程序。因此,您不能通过 App Group 在您的 iOS 应用程序和 WatchKit 扩展程序之间共享内容;你必须使用某种网络技术。许多人为此使用 WatchConnectivity。

    // 我浏览了很多在线教程……

    听起来这些教程是为旧版本的 watchOS 编写的,WatchKit 扩展在 iPhone 上运行。自从watchOS 2 之后,情况就不是这样了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 2018-03-10
      • 2021-07-28
      • 2017-10-16
      • 2021-02-20
      相关资源
      最近更新 更多