【问题标题】:Apple Watch: Is this a good way to allow apple watch app to grab new data?Apple Watch:这是让 Apple Watch 应用获取新数据的好方法吗?
【发布时间】:2018-08-24 15:37:27
【问题描述】:

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

这就是我将 API 密钥发送到我的 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];
}

这就是我在 Apple Watch 应用的用户默认值中存储 API 密钥的方式。我保存 API 密钥。然后,我使用 API 密钥发出请求。如果用户退出 iPhone 应用程序,我会删除默认的 API 密钥。

 // 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)
        } 
    }

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

【问题讨论】:

    标签: ios objective-c swift apple-watch


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2015-10-06
      • 2016-05-03
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多