Receive and respond to EKEventStoreChangedNotifica

2019-01-29 12:25发布

问题:

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!

回答1:

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.



回答2:

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.