【iOS 入门】extension

CFNotificationCenterGetDarwinNotifyCenter!这是CoreFoundation库中一个系统级的通知中心,苹果的系统自己也在用它,看清了“Darwin””了没有?哈哈!看了下CFNotificationCenter相关的API,跟NSNotificationCenter有点像。需要用到Toll-Bridge的知识与CoreFoundation相关的类进行桥接,这虽不常用但也不难。还需要注意下个别参数的使用。

// 添加监听

- (void)addObserver

{

CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();

CFNotificationCenterAddObserver(notification, (__bridge const void *)(self), observerMethod, CFSTR(“通知名”), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

}

void observerMethod (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)

{

//监听到notification后要做的处理

}

// 移除监听

- (void)removeObserver

{

CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();

CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR(“通知名“), NULL);

}

// 发送通知

- (void)postNotificaiton

{

CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();

CFNotificationCenterPostNotification(notification, CFSTR(“通知名”), NULL, NULL, YES);

}

使用这个方法后,容器App调用addObserver,扩展改变音量的时候调用 postNotificaiton ,容器App就能接收到通知了。

下一步是要传输数据,看看发送和接收的方法的参数,

void CFNotificationCenterPostNotification ( CFNotificationCenterRef center, CFStringRef name, const void *object, CFDictionaryRef userInfo, Boolean deliverImmediately );

void observerMethod (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)

还真有 CFDictionaryRef userInfo ,太好了,赶紧爽一下!

CFNotificationCenterPostNotification(notification, CFSTR(“通知名”), NULL, 数据, YES);



容器App接收到的 userInfo 居然是nil!!百思不得骑姐其解,只能看文档了:

 

CFNotificationCenterPostNotification 文档
妈蛋,传不过去!

but!无所谓啦~ㄟ( ▔, ▔ )ㄏ,一开始不是已经解决了共享数据的问题了么,扩展发送通知前先存储数据,容器App接收到通知后,再读取共享数据那就好了~~~用这个思路,就能实现大部分的扩展与容器App之间的交互功能了~

BTW,如果想实现更复杂的功能,推荐使用MMWormhole这个开源库,它专门用于在Container app 与 Extension间传递消息,苹果婊 Watch OS 也适用~

对了,如果用Jenkins打包,一定要注意widget 的app id (不是容器app 的app id)和app groups是正确的,否用 application loader提交程序的时候,会报错。



作者:十一点就要睡觉的码农
链接:https://www.jianshu.com/p/e807ee6e46e5
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。




先记个地址https://www.cnblogs.com/junhuawang/p/8178276.htm

猜你喜欢

转载自www.cnblogs.com/mamamia/p/12322991.html
今日推荐