From iPhone Development Wiki
Revision as of 05:42, 5 November 2012 by Yfrancis (talk | contribs) (Server)
Jump to: navigation, search

CPDistributedNotificationCenter is class that provides a subset of the functionality found in NSDistributedNotificationCenter on Mac OS X. It allows a process to send notifications globally without knowledge of listening clients. Interested clients can register for distributed notifications from a known server, and these notifications will be posted via the local NSNotificationCenter.


N.B. A server cannot immediately start posting notifications on creation. Even if a client process starts listening for notifications before the server runs, there is a minor delay incurred due to registration. Notifications sent by the server will only be sent to clients that have resulted in CPDistributedNotificationCenterClientDidStartListeningNotification being posted. A server can optionally watch for this notification (as well as CPDistributedNotificationCenterClientDidStopListeningNotification) and maintain a counter of listening processes. If there are no listening processes then the server can avoid, or defer posting notifications.



  // Center name must be unique, recommend using application identifier.
  CPDistributedNotificationCenter* notificationCenter;
  notificationCenter = [CPDistributedMessagingCenter centerNamed:@"unique.name.for.messaging.center.note"];
  [notificationCenter runServer]; // or runServerOnCurrentThread on iOS 4.x or earlier
  [notificationCenter retain];

  // Register to get notified of listening clients
  NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
  [nc addObserver:self


- (void)clientDidStartListening:(NSNotification*)note
  NSDictionary* userInfo = [note userInfo];
  CPDistributedNotificationCenter* notificationCenter = [note object];
  NSString* bundleIdentifier = [userInfo objectForKey:@"CPBundleIdentifier"];
  [notificationCenter postNotificationName:@"notification name" 
                                                    userInfo:[NSDictionary dictionaryWithObject:@"hello" forKey:@"message"]];
  // optionally call with toBundleIdentifier: to only send notification to this client (or any specific client)


CPDistributedNotificationCenter* notificationCenter;
notificationCenter = [CPDistributedNotificationCenter centerNamed:@"unique.name.for.messaging.center.note"];
[notificationCenter startDeliveringMessagesToMainThread];

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
             selector:@selector(gotNotification:) // this method will be called whenever the server posts a notification
                 name:nil // or name of the notification you are interested in