最近在进行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