手表连接
首先,两个应该相互通信的类(iOS 和 watchOS)需要符合<WCSessionDelegate>
and #import
the WatchConnectivity
框架
在发送数据之前,您需要检查您的设备是否能够发送数据
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
NSLog(@"WCSession is supported");
}
然后,如果您希望使用“交互式消息传递”(sendMessage API),您需要首先查看其他设备是否可以访问:
if ([[WCSession defaultSession] isReachable]) {
//Here is where you will send you data
}
“后台操作”API 不要求在您调用 WCSession API 时可以访问对应设备。
在应用程序之间传输数据时,您有多种选择,苹果文档 https://developer.apple.com/library/prerelease/ios/documentation/WatchConnectivity/Reference/WCSession_class/index.html#//apple_ref/occ/cl/WCSession它们是这样描述的:
Use the updateApplicationContext:error:
仅向对方传达最新状态信息的方法。当对方醒来时,它可以使用此信息来更新自己的状态并保持同步。使用此方法发送新字典会覆盖以前的字典。
Use the sendMessage:replyHandler:errorHandler:
or sendMessageData:replyHandler:errorHandler:
立即将数据传输给对方的方法。这些方法旨在当您的 iOS 应用程序和 WatchKit 扩展都处于活动状态时进行即时通信。
Use the transferUserInfo:
方法在后台传输数据字典。您发送的字典将排队等待传送给对方,并且当当前应用程序暂停或终止时传输将继续。
Use the transferFile:metadata:
方法在后台传输文件。如果您想要发送的不仅仅是简单的值字典,请使用此方法。例如,使用此方法发送图像或基于文件的文档。
我将给你一个如何发送/接收数据的例子应用上下文
发送数据:
WCSession *session = [WCSession defaultSession];
NSError *error;
[session updateApplicationContext:@{@"firstItem": @"item1", @"secondItem":[NSNumber numberWithInt:2]} error:&error];
接收数据:
- (void) session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {
NSLog(@"%@", applicationContext);
NSString *item1 = [applicationContext objectForKey:@"firstItem"];
int item2 = [[applicationContext objectForKey:@"secondItem"] intValue];
}
有关 WatchConnectivity 的更多信息,我强烈建议您观看WWDC2015 会议视频 http://developer.apple.com/videos/wwdc/2015/?id=713并阅读Apple 关于 WatchConnectivity 的文档 https://developer.apple.com/library/prerelease/ios/documentation/WatchConnectivity/Reference/WatchConnectivity_framework/index.html