我有XCode 7,带有iOS 9.1的iPhone6,带有WatchOS 2.0的Apple Watch(现在我更新到2.0.1)
我尝试在Watch和iPhone之间进行通信。
在iPhone上我启动我的单身人士
- (instancetype)init {
self = [super init];
if (self.isConnectivityAvailable) {
session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
return self;
}
- (BOOL)isConnectivityAvailable {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
return [WCSession isSupported];
} else {
return NO;
}
}
AppDelegate中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//custom code
(void)[AppConnectivityHandler instance]; //start App connectivity with Apple Watch
return YES;
}
这一切都很好
我按照那样处理消息
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler {
LOG(@"receive message");
NSString *request = message[kRequestKey];
__block NSDictionary *reply = @{};
dispatch_sync(dispatch_get_main_queue(), ^{
if ([request isEqualToString:kRequestDayInfo]) {
//formirate reply dictionary
}
});
LOG(@"send reply");
replyHandler(reply);
}
在我的手表上我在主界面控制器中调用函数时开始加载
- (void)willActivate {
[super willActivate];
if ([WatchConnectivityHandler instance].isConnectivityAvailable) {
[[WatchConnectivityHandler instance] loadDayInfoWithCompletion:^(NSError * _Nullable error, WatchDayInfo * _Nullable dayInfo) {
//code
}];
} else {
//error
}
}
我的手表单身人士
+ (nonnull instancetype)instance {
static WatchConnectivityHandler *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [WatchConnectivityHandler new];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self.isConnectivityAvailable) {
session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
return self;
}
- (BOOL)isConnectivityAvailable {
return [WCSession isSupported];
}
- (void)loadDayInfoWithCompletion:(void(^ _Nonnull)( NSError * _Nullable error, WatchDayInfo * _Nullable dayInfo))completion {
[session sendMessage:@{kRequestKey : kRequestDayInfo} replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
NSLog(@"reply");
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"%@", replyMessage);
//custom code
completion(nil, /*custom object*/);
});
} errorHandler:^(NSError * _Nonnull error) {
NSLog(@"error");
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"%@", error);
completion(error, nil);
});
}];
}
所以第一次工作正常,我得到回复。但后来我开始出现很多错误,比如
Error Domain=WCErrorDomain Code=7007 "WatchConnectivity session on paired device is not reachable."
Error Domain=WCErrorDomain Code=7014 "Payload could not be delivered."
我在Watch上测试,从iPhone获得回复通常是个问题,等待很长时间。但是在我测试的iPhone上,当它从Watch获得消息时,它会非常快速地发送回复,但我没有在Watch上看到该回复。
每次观看启动我的应用时,我都需要更新我的信息。有什么问题?也许我使用的功能不正确?
答案 0 :(得分:-2)
使用transeruserinfo方法而不是sendmessage并使用didreceiveuserinfo方法而不是didreceiveapplicationcontext。