【发布时间】: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