ios - WCSession 只工作一次

标签 ios objective-c watchos watchconnectivity wcsession

在我的应用程序中,我必须将信息从 watch InterfaceController 发送到手机 HomeViewController。但是,当我运行我的代码时,这些信息只有效一次。为了让它再次运行,我必须删除 Apple Watch 应用并重新安装。

InterfaceController.m:

#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>

@interface InterfaceController() <WCSessionDelegate>

@property (strong, nonatomic) WCSession *session;

@end

@implementation InterfaceController

-(instancetype)init {
    self = [super init];

    if (self) {
        if ([WCSession isSupported]) {
            self.session = [WCSession defaultSession];
            self.session.delegate = self;
            [self.session activateSession];
        }
    }
    return self;
}

-(void)sendText:(NSString *)text {

    NSDictionary *applicationDict = @{@"text":text};
    [self.session updateApplicationContext:applicationDict error:nil];

}

- (IBAction)ButtonPressed {
    [self sendText:@"Hello World"];

}

HomeViewController.m:

#import "HomeViewController.h"
#import <WatchConnectivity/WatchConnectivity.h>

@interface HomeViewController ()<WCSessionDelegate>
@end

@implementation HomeViewController
@synthesize TextLabel;

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([WCSession isSupported]) {
        WCSession *session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];
    }  
}

- (void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {

    NSString *text = [applicationContext objectForKey:@"text"];

    dispatch_async(dispatch_get_main_queue(), ^{
        [TextLabel setText:text];
    });
}

如前所述,iOS 标签只会更改为“Hello World”一次。在我重新启动 iOS 应用程序后,它的文本标签不再显示“Hello World”,我无法让 watch 再次将 iOS 文本标签更改回“Hello World”。

这是 watch 和iPhone通信的问题,还是代码的问题?

最佳答案

根据 updateApplicationContext 的意图,这是代码的问题:

you should use this method to communicate state changes or to deliver data that is updated frequently

在您的情况下,您正在尝试将未更改 应用程序上下文从 watch 重新发送到手机。

由于之前的应用程序上下文没有变化,手机不会收到与之前收到的任何不同的东西, watch 没有理由(重新)传输任何东西,所以它不会。

这是 Apple 在 Watch Connectivity 中设计的一项优化。

如何解决这个问题?

  • 您可以重新设计您的应用,以消除重新传输相同数据的需要。

  • 如果您的应用必须第二次重新传输相同的信息,您必须改变您的方法:

    • You can add additional data (例如 UUID 或时间戳)到应用程序上下文,以确保您发送的更新与之前的应用程序相同您发送的上下文。

    • 使用不同的 WCSession 功能,例如 sendMessage,它可以让您再次发送相同的数据。

关于ios - WCSession 只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38780719/

相关文章:

ios - 购买历史记录中的inApp购买待定

iphone - Objective-C,.m/.mm 性能差异?

ios - WatchKit 项目无法识别 presentAudioRecordingControllerWithOutputURL

android - 免费的条形码图像解码库

ios - Google 自定义搜索 API 返回访问未配置(iOS 应用程序)

android - 如何更改 react-native 中的默认 fontFamily

watchos - 是否有每个 watchOS 界面支持哪些复杂功能系列的完整列表?

ios - 在新 Apple Watch Series 2 WatchOS 3 中使用 GPS

iOS:启动具有多个收件人的消息应用程序

ios - 如何从日历中获取所有事件(Swift)