我正在尝试使用此类从后台守护程序发布通知,以便其他进程中的多个客户端可以接收这些通知并对其进行 *** 作.我意识到还有其他选择,包括CPdistributedMessagingCenter或CFMessagePort,低级mach端口甚至是darwin的notify_post.如果守护进程不了解客户端,我更喜欢它,并且我希望能够将数据与通知一起传递,并且notify_post不允许这样做.
目前,这就是我在守护进程中所做的事情:
CPdistributedNotificationCenter* center;center = [CPdistributedNotificationCenter centernamed:@"com.yfrancis.notiftest"];[center runServer];[center postNotificationname:@"hello"];
在客户端:
CPdistributedNotificationCenter* center;center = [CPdistributedNotificationCenter centernamed:@"com.yfrancis.notiftest"];[center startDeliveringNotificationsToMainThread];NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];[nc addobserver:[Listener new] selector:@selector(gotNotification:) name:@"hello" object:nil];
其中Listener是一个实现单个方法gotNotification的简单类:
不幸的是,客户端从未收到“hello”通知.如果我用nil替换addobserver调用中的name参数,我可以看到每个通知都传递给客户端的通知中心,但“hello”不是其中之一.
通过查看SpringBoard和CPdistributedNotificationCenter的反汇编,我获得了代码的灵感.通知似乎通过CPdistributedNotificationCenter的deliverNotification:userInfo传递:它充当NSNotificationCenter的postNotificationname:object:userInfo:的填充程序.
我在这里错过了什么?
解决方法 弄清楚了.在发送通知之前,您的守护程序必须等待指示客户端已开始侦听的通知.没有积压,即使守护程序服务器在客户端之前运行,也存在注册延迟.您不能简单地启动服务器并立即向听众发布通知.以下适用于我:在服务器init中:
self.center = [CPdistributedNotificationCenter centernamed:@"com.yfrancis.notiftest"];[self.center runServer];// requires a runloopNSNotificationCenter* nc = [NSNotificationCenter defaultCenter];[nc addobserver:self selector:@selector(clIEntEvent:) name:@"CPdistributedNotificationCenterClIEntDIDStartListeningNotification" object:self.center];
并确保在服务器中实现以下方法:
- (voID)clIEntEvent:(NSNotification*)notification{ // you can Now send notifications to the clIEnt that caused this event // and any other clIEnts that were registered prevIoUsly [self.center postNotificationname:@"hello!"];{
我在iPhoneDevWiki上记录了这个API
总结以上是内存溢出为你收集整理的objective-c – 如何接收通过CPDistributedNotificationCenter发布的通知全部内容,希望文章能够帮你解决objective-c – 如何接收通过CPDistributedNotificationCenter发布的通知所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)