在 watchOS2 中使用 WatchConnectivity 在 iOS 和 WatchOS 之间发送消息

Send messages between iOS and WatchOS with WatchConnectivity in watchOS2

看了WWDC2015,发现现在可以在手表上开发原生应用了。这开启了很多功能,我想知道如何在我的 iOS 应用程序和我的 AppleWatch 应用程序之间发送数据。

我看到有一个名为 WatchConnectivity 的新框架。我如何使用它以及来回发送数据时我有哪些选择?

WatchConnectivity

首先,应该相互通信的两个 类(iOS 和 watchOS)需要符合 <WCSessionDelegate>#import WatchConnectivity 框架

在发送数据之前,您需要检查您的设备是否能够发送数据

if ([WCSession isSupported]) {
      WCSession *session = [WCSession defaultSession];
      session.delegate = self;
      [session activateSession];
      NSLog(@"WCSession is supported");
}

然后如果你想使用 "interactive messaging" (sendMessage APIs) 你需要先看看其他设备是否可达:

if ([[WCSession defaultSession] isReachable]) {
    //Here is where you will send you data
}

"background operations" API 不需要在您调用 WCSession API.

的时间点可以访问对应设备

在应用程序之间传输数据时,您有多种选择,在 Apple Documentation 中,它们是这样描述的:

  • 使用updateApplicationContext:error:方法只将最新的状态信息传递给对方。当对方醒来时,它可以使用此信息来更新自己的状态并保持同步。使用此方法发送新字典会覆盖以前的字典。

  • 使用sendMessage:replyHandler:errorHandler:sendMessageData:replyHandler:errorHandler:方式,立即向对方传输数据。当您的 iOS 应用程序和 WatchKit 扩展都处于活动状态时,这些方法旨在用于即时通信。

  • 使用transferUserInfo:方式在后台传输数据字典。您发送的词典正在排队等待发送给对方,当当前应用程序暂停或终止时,传输将继续。

  • 使用transferFile:metadata:方式在后台传输文件。如果您想要发送的不仅仅是一个简单的值字典,请使用此方法。例如,使用此方法发送图像或基于文件的文档。

我会给你一个例子如何send/receive数据与Application Context

发送数据:

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 session video and reading the Apple Documentation on WatchConnectivity