【问题标题】:How to receive notifications posted via CPDistributedNotificationCenter如何接收通过 CP DistributedNotificationCenter 发布的通知
【发布时间】:2012-11-03 18:02:26
【问题描述】:

iOS 上的私有 AppSupport 框架有一个名为 CPDistributedNotificationCenter 的类,它似乎支持 OS X 上 NSDistributedNotificationCenter 提供的功能的子集。

我正在尝试使用此类从后台守护程序发布通知,以便其他进程中的多个客户端可以接收这些通知并对其采取行动。我意识到还有其他选择,包括CPDistributedMessagingCenterCFMessagePort、低级马赫端口甚至达尔文的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: 的简单类

不幸的是,客户端从未收到“你好”通知。如果我用nil 替换addObserver 调用中的name 参数,我可以看到发送到客户端通知中心的每个通知,但“你好”不是其中之一。

我通过查看 SpringBoardCPDistributedNotificationCenter 的反汇编获得了我的代码的灵感。通知似乎是通过CPDistributedNotificationCenterdeliverNotification:userInfo: 传递的,它充当NSNotificationCenterpostNotificationName:object:userInfo: 的垫片。

我在这里错过了什么?

【问题讨论】:

  • XPC 怎么样,每个进程都可以与守护进程保持双向连接?还是XPC,加上notify_post?一个缺点是 XPC 是 iOS5+。我认为 XPC 是使用守护进程作为后端的库的新标准。
  • 我不希望守护进程对客户端有任何了解。 XPC 打败了这一点,我只想触发一次性通知,如果有任何感兴趣的客户,他们可以对其采取行动。
  • Activator 使用注册机制,CPDistributedMessagingCenter 需要远程中心名称才能向其发送消息,因此需要了解客户端

标签: objective-c ios cocoa ipc


【解决方案1】:

想通了。在发送通知之前,您的守护程序必须等待指示客户端已开始侦听的通知。没有积压,即使守护程序服务器在客户端之前运行,也存在注册延迟。您不能简单地启动服务器并立即向侦听器发布通知。以下对我有用:

在服务器初始化中:

self.center = [CPDistributedNotificationCenter centerNamed:@"com.yfrancis.notiftest"];
[self.center runServer];

// requires a runloop
NSNotificationCenter* 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多