AppleWatch与App间的通信

 最近在进行applewatch的开发,打算做一个微信的demo出来。

由于数据处理和业务逻辑都会放在app端,watchkit只是用来展示用途,在app处于非激活的状态下无法进行请求的问题还未解决,这个demo只是watch和app简单的相互传值通信。其中app端中CFNotificationCenterPostNotification 方法中的userInfo参数无法成功传值到watch端中,还在尝试用其他的方法实现,解决到这个问题的朋友麻烦留言探讨一下实现方案。

 

从app端传值到watch端:

 

发送端:

CFStringRef observedObject = CFSTR("xiaok");
    NSMutableDictionary *userInfo2 = [NSMutableDictionary new];
    [userInfo2 setValue:@"PicName" forKey:@"PicName"];
    [userInfo2 setValue:@"Source" forKey:@"Source"];
    CFDictionaryRef userInfo = (__bridge CFDictionaryRef)(userInfo2);
    CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),(__bridge CFStringRef)@"xiaok",observedObject,userInfo,YES );

 

接受端:

- (void) watchForDataChanges {
    // Listen for notifications on Darwing
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                    (__bridge const void *)(self),
                                    NotificationReceivedCallback,
                                    CFSTR("xiaok"),
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cocoaNotificationCallBack) name:@"playersChangedCocoa" object:nil];
}

static void NotificationReceivedCallback(CFNotificationCenterRef center,
                                         void *observer, CFStringRef name,
                                         const void *object, CFDictionaryRef
                                         userInfo)
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playersChangedCocoa" object:nil];
}

void darwinNotificationCenterCallBack() {
    NSLog(@"Notification received from iPhone app!");
    
    // Go from Darwin to Cocoa land
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playersChangedCocoa" object:nil];
}


- (void) cocoaNotificationCallBack {
    NSLog(@"Notification received from ourselves in Cocoa");
    [self.displayLB setText:@"app点击了噢"];
    
}

 

从watch传值到app端:

发送端:

- (IBAction)btnClick1 {
    [WKInterfaceController openParentApplication:@{@"tag":@"1"} reply:^(NSDictionary *replyInfo, NSError *error) {
    }];
}

 

接受端:在appdelegate.m

-(void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
    NSString *type = userInfo[@"tag"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WATCH_CLICK" object:type];
}

 

 

demo github:https://github.com/lkjxshi/WatchToAppDemo.git

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值