在iPhone和iWatch之间发送数据

时间:2016-02-27 10:10:16

标签: objective-c iphone watchkit watch-os-2

下面的代码有助于将从iWatch发送到iPhone的数据。但如果我们编写代码-(void)send:(NSString *)action并在Appdelegate

中,则不能从iPhone发送到iWatch
 (void)session:(nonnull WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void(^)(NSDictionary<NSString *,id> *))replyHandler in wacth extension

在手表扩展控制器中

 -(void)send:(NSString *)action 
  {
    NSDictionary *request = @{@"request":action};
    [[WCSession defaultSession] sendMessage:request
      replyHandler:^(NSDictionary *replyHandler) {
     [self setTextForLabelWithData:[replyHandler valueForKey:@"response"]];
         }
     errorHandler:^(NSError *error) {
          NSLog(@"");
    }];
}

在Appdelegate中

- (void)session:(nonnull WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void(^)(NSDictionary<NSString *,id> *))replyHandler
  { 
    NSString *action = message[@"request"];
    NSString *actionPerformed;
    if ([action isEqual:@"foo"]) {
        // do "foo" stuff
        actionPerformed = @"foo done";
    } else if ([action isEqual:@"bar"]) {
        // do "bar" stuff
        actionPerformed = @"bar done";
    }
    replyHandler(@{@"actionPerformed":actionPerformed});
}

怎么做?请帮忙。

2 个答案:

答案 0 :(得分:0)

我猜您需要更新&#34;响应&#34;在这一行

 [self setTextForLabelWithData:[replyHandler valueForKey:@"response"]];

to&#34; actionPerformed&#34;就像那样:

 [self setTextForLabelWithData:[replyHandler valueForKey:@"actionPerformed"]];

答案 1 :(得分:0)

您需要将iPhone的Watch Connectivity委托方法请求实施到Apple Watch和Apple Watch到iPhone。

有关详细信息,请参阅教程:http://www.codingexplorer.com/watch-connectivity-swift-application-context/