【问题标题】:Xcode Swift appleWatch read application UserDefaults?Xcode Swift appleWatch 读取应用程序 UserDefaults?
【发布时间】:2019-11-26 15:30:55
【问题描述】:

我正在尝试从 AppleWatch 扩展中读取应用程序 UserDefaults,在研发失败 2 天后,我发布了这个帖子。

例如,我要做的是使用以下代码(即使应用程序终止)确定用户是否登录或不形成 appleWatch 端:

struct ContentView: View {

    let auth_token:String = UserDefaults(suiteName: "group.mybundle.app.com")!.string(forKey: "token") ?? ""

    @ViewBuilder
    var body: some View {

        if self.auth_token == "" {
             Text("You need to be Logged in").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
        }else{
              WebImage(imageURL: URL(string: token)).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
        }

    }
}

一旦用户成功登录,从应用程序端:

   UserDefaults(suiteName: "group.mybundle.app.com")!.set(rr, forKey: "token")
   UserDefaults(suiteName: "group.mybundle.app.com")!.synchronize()

我仍然无法阅读token

从 appleWatch 扩展读取父应用程序数据UserDefaults 的最简单方法是什么?

【问题讨论】:

    标签: ios swift xcode swiftui


    【解决方案1】:

    here 所讨论的那样,似乎已弃用或不推荐将应用组从 iOS 应用共享到 Apple Watch。

    将数据从 iOS 应用程序传输到 WatchOS 应用程序的一种方法是使用 WatchConnectivity 框架。 Here 是 Apple 的官方文档。

    注意事项: 1.in cases when your watch app is running in the background

    1. 还有here're some sample codes

    2. A sample app from Apple

    【讨论】:

    • 查看上面 bkwebhero 的评论。我认为这是正确的。
    【解决方案2】:

    正如顺哲所说,您不能再在 iOS 和 WatchOS 之间共享UserDefaults

    您可以使用WatchConnectivitysendMessage:replyHandler:errorHandler 方法来唤醒iPhone,运行一些代码,然后将一些内容发送回手表。

    More info here.

    【讨论】:

    • 是的,如果它被终止,它应该启动 iPhone 应用程序。唯一的要求是将 WCSession 的 isReachable 属性设置为 true。当 iPhone 在范围内并且手表扩展程序在前台运行或在后台以高优先级运行时,就会发生这种情况。 (锻炼、并发症刷新等)
    • 如果您有 github 链接或任何小项目,能否解释一下当手机终止时我如何从手机获取数据?信不信由你,我仍然无法做到这一点,哈哈,我差点把手表弄坏了
    猜你喜欢
    • 2018-04-29
    • 2018-12-12
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多