简体   繁体   中英

WatchOS 2.0 Sharing Data between iOS App and WatchOS App

Previous I used NSUserDefaults to share basic variables between the watch and app.

My goal is to display the user's email address on the watch which is stored on the iPhone app NSUserDefaults. I understand that after Watch v1, you cannot use App Groups anymore to share data.

I understand you need to use the Watch Connectivity API but I can only figure out how to use it when an action happens. Not before the Watch App is started.

Let me know if you have any ideas.

Yes, you can store the email in NSUserDefaults on iPhone, and display it on the Watch. To do so, you need to send a message to the iPhone using the Watch Connectivity API, and when you receive this message respond with the email address you grab from NSUserDefaults. This can occur once the app on the Watch is launched, but not before then. You could cache it on the Watch for future use if you don't wish to have to ask the iPhone for it every time. If it changes on the iPhone you can message the Watch to update it there as well.

Here's some example code to show how to make the request from the Apple Watch in Swift and respond to it on the iPhone in Objective-C.

Somewhere in your Watch app's code after launch:

if WCSession.defaultSession().reachable {
    WCSession.defaultSession().sendMessage(["email-request": "email"], replyHandler: { (reply: [String : AnyObject]) -> Void in
        //success
        dispatch_async(dispatch_get_main_queue()) {
            if let email = reply["email-request"] as? String {
                //store the email, display it, etc
            }
        }
    }, errorHandler: { (error: NSError) -> Void in
        dispatch_async(dispatch_get_main_queue()) {
            //couldn't get email, maybe show error message
        }
    })
} else {
    //iPhone not available, maybe show error message
}

In your iPhone app's AppDelegate:

- (void)session:(nonnull WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * __nonnull))replyHandler
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (message[@"email-request"]) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            replyHandler(@{@"email-request": @([defaults stringForKey:@"email"])});
        }
    });
}

Note that both the app delegate and extension delegate have to adopt the WCSessionDelegate protocol and they need to be properly activated. See the Watch Connectivity Framework Reference for additional information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM