ios - 苹果 watch : Is this a good way to allow apple watch app to grab new data?

标签 ios objective-c swift apple-watch

目前,我正在构建一个类似于邮件应用程序的 Apple Watch 应用程序。我正在将 API key 从我的 iOS 应用程序发送到我的 Apple Watch 应用程序,并使用 API key 从我的 Apple Watch 发出请求。

这就是我将 API key 发送到我的 Apple Watch 应用程序的方式。

NSDictionary *applicationDict = @{@"apiKey" : apiKey };

if ([WCSession defaultSession].reachable) {
    [[WCSession defaultSession] sendMessage:applicationDict replyHandler:^(NSDictionary *replyHandler) {

    } errorHandler:^(NSError *error) {

    }];
} else {
    [session  updateApplicationContext:applicationDict error:nil];
}

这就是我将 API key 存储在我的 Apple Watch 应用的用户默认设置中的方式。我保存 API key 。然后,我使用 API key 发出请求。如果用户曾经退出 iPhone 应用程序,我会在默认情况下删除 API key 。

 // receive apiKey if watch app is in the foreground
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    if let apiKeyString = message[@"apiKey"] as? String{
        defaults.set(apiKeyString, forKey:kApiKey)
        syncMail(apiKey: apiKeyString)
    } 
}

// receive apiKey if watch app is in the background
    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        if let apiKeyString = applicationContext[@"apiKey"] as? String{
            defaults.set(apiKeyString, forKey:kApiKey)
            syncMail(apiKey: apiKeyString)
        } 
    }

这对我来说似乎很管用。但是,我不确定这是否是最好的方法。我想知道是否有任何方法可以改进我的方法?任何提示或建议表示赞赏。

最佳答案

只有当您的 watch 连接到您的手机时,这才有效。您可以使用 updateapplicationContext 来保证将 apikey 传递给 Apple Watch。

您传递的似乎是您登录时生成的 token ,因此您应该将其保存在钥匙串(keychain)中。

关于ios - 苹果 watch : Is this a good way to allow apple watch app to grab new data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007710/

相关文章:

iphone - UIActivity 指示器不显示

ios - 从 xcode 中的 mainBundle 获取子目录

ios - 可以在 EAGLView 中使用 UIKit 吗?

ios - 当键仅检索 1 个对象时如何向对象添加数据? PARSE.COM swift

swift - cell.textLabel.text 未附加

ios - 如何在 iOS 图表上正确显示底轴 (xVals) 上的标签?

ios - 如何从 UIPickerView 获取选定的值

ios - 当我的应用程序通过 UITabBar 完成启动时,如何将加载的数据传递到 UITableView?

ios - UISlider 边界和框架宽度返回不正确的值

objective-c - 让 __PRETTY_FUNCTION__ 只打印选择器的第一部分?