Apple Watch:这是一个让苹果手表应用程序获取新数据的好方法吗?

问题描述 投票:5回答:1

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

这就是我将API密钥发送到Apple Watch App的方式。

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密钥存储在Apple Watch应用程序的用户默认值中的方法。我保存了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个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.