WatchOS 2 - iOS UserDefaults 共享 [英] WatchOS 2 - iOS UserDefaults sharing

查看:65
本文介绍了WatchOS 2 - iOS UserDefaults 共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 iOS 和 WatchOS 2 之间同步用户详细信息.在以前版本的 WatchKit 应用程序组中共享此类首选项非常好,但在版本 2 中我正在为此苦苦挣扎.

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.

现在我尝试使用 WCSessiontransferUserInfo: 方法发送 userInfo,然后将该 userInfo 保存到 watchOS 的 userDefaults.但问题是对于这样的细节手表必须首先要求 iPhone 发送 UserInfo.如果没有使用 iPhone 应用程序,那么在这种情况下 Watch App 不会反映 userInfo 的变化.

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.

有人对 WatchOS 2 中的这种实现有想法吗?我做得对吗,请建议是否有人对此有所了解.

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

推荐答案

如果您在手表上使用 WCSessionsendMessage API,它将唤醒 iOS 应用程序如果它尚未运行,则为后台.所以你可以这样做:

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:

手表扩展代码:

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

iOS 应用代码:

- (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

这篇关于WatchOS 2 - iOS UserDefaults 共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆