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
相关推荐
88731798 2019-12-02
WatchKit开发 2019-11-12
81701494 2015-06-27
88731798 2019-01-10
88731798 2018-09-03
89701697 2018-06-30
81761796 2017-09-15
苹果大牛 2016-01-11
Pineapple 2016-01-05
89701697 2015-06-18
81761796 2015-06-11
dfx0 2015-06-08
89701697 2015-05-21
WatchKit开发 2015-05-20
81761796 2015-05-14
89701697 2015-05-14
88731798 2015-05-10
87761995 2015-05-04