iOS — Sending Notifications between your apps

How to notify from one of your app to be notified from your another app.

This was one of problem I faced while I was working on iOS8 new feature extensions (Document Provider Extension).

When you add any extensions to your project you have add it as a target to your current app. I made sure to share Functionality code and Coredata for Container app and Extension since Extension is just a part of Main Container app. When some data is changed in Container app and you want your Extension also update itself for new changes we need some type of notification to do that.

Solution I tried to solve this is

  1. Normal NSNotificationCenter — Wont Work between apps only inside the app

  2. Using of KVO for Shared UserDefaults between main app and extension— Wont work

  3. When I browsed net for few hours and some one suggested to use NSFileCoordinator and NSFilePresenter where you can write into a file in shared container and receive when change in Extension target, but we felt its too much complicated just for simple thing.

  4. Then CFNotificationCenterGetDarwinNotifyCenter came to rescue.

How CFNotificationCenterGetDarwinNotifyCenter Works

This is a type of system level notification in core foundation, even system also uses these notifications. Using this is very simple for my problem.

Writing Code:

Below code will just shows how to add observer for this type of notifications. Your reciever app should add itself as a observer for notificaiton with notificaiton name given <notificaiton name>. Both Container app and Extension should use same name of notificaiton.

- (void)someMethod {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter (); // 1
 (__bridge const void *)(self), observerMethod, CFSTR(“<notificaiton 
name>”), NULL, CFNotificationSuspensionBehaviorDeliverImmediately); 
// 2
 observerMethod (CFNotificationCenterRef center, void *observer, 
CFStringRef name, const void *object, CFDictionaryRef userInfo)
{ // Your custom work } // 3

Posting of notification sample code

- (void)postNotificaiton {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
CFNotificationCenterPostNotification(notification, CFSTR(“<notificaiton name>”), NULL, NULL, YES);

Removing observer from notification

CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR(“
<notificaiton name>
”), NULL);

For more information

I hope this helped a iOS devs who are having same problem.


Powered By Z-BlogPHP 1.5.1 Zero

Copyright Rights Reserved.