简体   繁体   中英

WatchOS 2 - iOS UserDefaults sharing

I am trying to sync user detail in between iOS and WatchOS 2. In previous version of WatchKit App groups was pretty good to share such preferences but in version2 I am struggling for the same.

Right now i tried to send userInfo using WCSession 's transferUserInfo: method and then saving that userInfo into watchOS's userDefaults. But issue is For such detail watch has to first ask iPhone to send UserInfo. If iPhone application is not being used then in that case Watch App is not getting reflection of changes in userInfo.

Do anyone have idea for such implementation in WatchOS 2 ? Am I doing right thing please suggest if anyone have knowledge of this.

If you use WCSession 's sendMessage API on the watch it will wake the iOS app up in the background if it is not already running. So you could do something like:

watch extension code:

[[WCSession defaultSession] sendMessage:@{@"cmd":@"sendUpdate"} replyHandler:nil errorHandler:^{ /*handle errors*/ }]

iOS app code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    <...>
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
    <...>
}

- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error {
}

- (void)sessionDidBecomeInactive:(WCSession *)session
{}

- (void)sessionDidDeactivate:(WCSession *)session
{
    [session activateSession];
}

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message {
    NSString *cmd = message[@"cmd"];
    if ([cmd isEqual:@"sendUpdate"]) {
        [self sendUpdate];
    }
}

- (void)sendUpdate {
    WCSession *session = [WCSession defaultSession];
    if (session.isWatchAppInstalled && session.activationState == WCSessionActivationStateActivated) {
        [[WCSession defaultSession] transferUserInfo:[self dictionaryFullOfUpdates]];
    }
}

This is obviously simpler than what you'd probably do, but should give you the idea

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