在我的应用程序中,我必须将信息从手表InterfaceController发送到电话HomeViewController。但是,当我运行我的代码时,信息只工作一次。为了让它再次工作,我必须删除Apple应用程序并重新安装它。
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“。在我重新启动iOS应用程序,它的文本标签不再说"Hello“之后,我无法让手表将iOS文本标签再次更改为"Hello”。
这是手表和iPhone之间的通信问题,还是代码方面的问题?
发布于 2016-08-05 04:48:17
这是代码的一个问题,基于updateApplicationContext的意图
您应该使用此方法来传递状态更改或频繁传递更新的的数据。
在您的示例中,您试图将未更改的应用程序上下文从手表发送到电话。
由于与以前的应用程序上下文没有任何变化,并且手机不会收到任何与先前接收的不同的信息,所以没有理由让手表(重新)传输任何内容,所以它不会。
这是一个优化,苹果公司设计成手表连接。
如何解决这个问题?
- [You can add additional data](https://stackoverflow.com/a/37887812/4151918) (such as a `UUID` or timestamp) to the application context, to ensure that the update you're sending is _**not**_ identical to the previous application context you sent.
- Use different `WCSession` functionality, such as `sendMessage`, which would let you resend identical data a second time.
https://stackoverflow.com/questions/38780719
复制相似问题