WatchOS 2.0 Sharing Data between iOS App and WatchOS App

半城伤御伤魂 提交于 2020-01-06 22:03:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/34457888/watchos-2-0-sharing-data-between-ios-app-and-watchos-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!