Search code examples
iosobjective-cswiftapple-watch

Apple Watch: Is this a good way to allow apple watch app to grab new data?


Currently, I am building an apple watch app similar to the mail app. I am sending the API key from my iOS app to my Apple Watch App and using the API key to make requests from my Apple Watch.

This is how I send the API key to my 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];
}

This is how I store the API key in user defaults for my apple watch app. I save the API key. Then, I use the API key to make requests. If the user ever logs out of the iPhone app, I remove the API key in defaults.

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

This seems to work well for me. However, I am not sure if this is the best way. I was wondering if there is any way I can improve my method? Any tips or suggestions are appreciated.


Solution

  • This will only work if you watch is connected to your phone. You can use updateapplicationContext to guarantee the apikey will be passed to Apple Watch.

    It seems like what you are passing is the token generated when you log in so you should save it in keychain instead.