在WatchOS2之间,通过WatchConnectivity在iOS和WatchOS之间发送消息

我看了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");
}

然后,如果您希望使用“交互式消息传递”(sendMessage API),则需要先查看其他设备是否可达:

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

“后台操作”API在您调用WCSession API的时候不需要对方设备可访问.

在您的应用程序之间传输数据时,您有几个选择,在Apple Documentation中,它们的描述如下:

>使用updateApplicationContext:error:方法只将最近的状态信息传达给对方.当对方醒来时,它可以使用此信息更新自己的状态并保持同步.使用此方法发送新字典将覆盖以前的字典.
>使用sendMessage:replyHandler:errorHandler:或sendMessageData:replyHandler:errorHandler:将数据立即传输到对方.当您的iOS应用程序和WatchKit扩展程序都处于活动状态时,这些方法用于立即通信.
>使用transferUserInfo:方法在后台传输数据字典.您发送的字典排队等待交付给对方,并在当前应用程序暂停或终止时继续传输.
>使用transferFile:metadata:方法在后台传输文件.如果您想发送多个简单的值字典,请使用此方法.例如,使用此方法发送图像或基于文件的文档.

我将给你一个如何使用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并阅读Apple Documentation on WatchConnectivity

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...