2012-11-03 42 views
4
發佈通知

iOS上的私人AppSupport框架有一個名爲CPDistributedNotificationCenter類,它似乎支持由NSDistributedNotificationCenter在OS X提供的功能的子集如何接收通過CPDistributedNotificationCenter

我試圖使用此類發佈來自後臺守護進程的通知,以便其他進程中的多個客戶端可以接收這些通知並對其執行操作。我意識到還有其他選項,包括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:

一個簡單的類

不幸的是,客戶端永遠不會收到'hello'通知。如果我用nil替換addObserver調用中的name參數,我可以看到每個通知都發送到客戶的通知中心,但'hello'不是其中的一個。

我通過查看SpringBoardCPDistributedNotificationCenter的反彙編獲得了我的代碼的靈感。通知似乎通過CPDistributedNotificationCenterdeliverNotification:userInfo:遞送,其作爲NSNotificationCenter的墊片postNotificationName:object:userInfo:的墊片。

我在這裏錯過了什麼?

+0

XPC,其中每個進程可以保持與守護進程的雙​​向連接?還是XPC,加上notify_post?一個缺點是XPC是iOS5 +。我認爲XPC是圖書館的新標準,守護進程充當後端。 – conradev

+0

我不希望守護進程有任何客戶知識。 XPC擊敗了我,我只想發射一次性通知,如果有任何感興趣的客戶,他們可以採取行動。 – yfrancis

+0

Activator使用註冊機制,CPDistributedMessagingCenter需要遠程​​中心名稱來發送消息,因此需要客戶端的知識 – yfrancis

回答

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!"]; 
{ 

我已經證明這個API的iPhoneDevWiki