4

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

我正在尝试使用此类从后台守护程序发布通知,以便其他进程中的多个客户端可以接收这些通知并对其采取行动。我意识到还有其他选项,包括CPDistributedMessagingCenteror 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];

whereListener是一个实现单个方法的简单类gotNotification:

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

我通过查看SpringBoardand的反汇编获得了我的代码的灵感CPDistributedNotificationCenter。通知似乎是通过CPDistributedNotificationCenter's传递的deliverNotification:userInfo:,它充当 's 的NSNotificationCentershim postNotificationName:object:userInfo:

我在这里想念什么?

4

1 回答 1

5

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

在服务器初始化中:

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

于 2012-11-03T23:30:12.613 回答