如何在Objective-C中将数据从Iphone发送到OS2中的Apple Watch

Dav*_*nte 5 objective-c ios apple-watch watchkit

我已经看到了一个关于如何在Swift中来回发送数据的类似问题.我在Objective-C中问同样的问题.我也看过Apple的转型文档.

我最好用清晰的例子而不是讲座材料.因此,如果某人实施了这一点并且不介意分享,那将非常感激.

Phi*_*lip 22


以下是关于WatchConnectivity的Q/A链接:在watchOS2中使用WatchConnectivity在iOS和WatchOS之间发送消息


我将以ApplicationContext为例给出一个示例,WatchConnectivity还有其他两种消息传递技术.请观看WWDC2015会话视频.

首先,您需要符合要发送的类中的WCSessionDelegate协议并从/接收数据.例如手表和iPhone.

之前的基本检查:(这只是一个例子,实现比这更好)

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

    //Objective-C
    if ([[WCSession defaultSession] isReachable]) {
        NSLog(@"SESSION REACHABLE");
    }
Run Code Online (Sandbox Code Playgroud)

这会将数据从手机发送到手表.

WCSession *session = [WCSession defaultSession];
NSError *error;

[session updateApplicationContext:@{@"firstItem": @"item1", @"secondItem":[NSNumber numberWithInt:2]} error:&error];
Run Code Online (Sandbox Code Playgroud)

这将从手表上的手机接收数据.

- (void) session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {

    NSLog(@"%@", applicationContext);


    item1 = [applicationContext objectForKey:@"firstItem"];
    item2 = [[applicationContext objectForKey:@"secondItem"] intValue];
}
Run Code Online (Sandbox Code Playgroud)

关于WatchConnectivity的WWDC2015视频非常棒,我建议您查看它.

  • 这个网站非常有帮助.伟大的年轻人.`'https://github.com/kristinathai` (2认同)