Question

I was wondering if in iOS7, with the new API's it was finally possible to respond to a notification in the background, in my case, I have the following observer:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(storeChanged:)
                                             name:EKEventStoreChangedNotification
                                           object:eventStore];

I am receiving the notification perfectly but i need to run the app so that the selector gets called. I've browsed through the response and they say it's not possible but not sure if they where referring to iOS7 specifically.

Any thoughts?

Thanks!

Was it helpful?

Solution

The EKEventStoreChangedNotification will only fire when your app comes to the foreground. However if you want to call your storeChanged: method in the background, and thus having the UI already updated on coming to foreground again, you need to add the Background Fetch capability to your app.

<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
</array>

In your app delegate didFinishLaunchingWithOptions method add the line

[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

This ensures your app actually calls your background fetch, as the default interval is never. This minimum key is the key that ensures iOS handles when to call your background fetch method. You can set your own minimum interval if you don't want it to fire as often as possible.

Finally implement the background fetch method in your app delegate:

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
 [self storeChanged:nil];
 completionHandler(UIBackgroundFetchResultNewData);
}

You can test in Xcode while debugging from Debug > Simulate Background Fetch.

OTHER TIPS

Firstly when the app is in the background you can only run methods using the background task APIs to call a method after you've been backgrounded (as long as your task doesn't take too long - usually ~10 mins is the max allowed time). This applies to all versions of iOS even iOS7.

Read this question for more clarifications.

App States and Multitasking Guide by Apple can give you more clarifications on background handling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top