swift/ios refreshing app data when in background

2019-02-03 14:07发布

问题:

I'm writing a iOS/Swift application which reads data from a REST service each X minutes and updates the UI accordingly.

Now I would like that when the app is put in the background, a task keeps being invoked at X minutes intervals reading from the REST service and, in case the data just read satisfies a given condition, show a notification prompting the user to bring the app back to the foreground.

In my searches I've read that during applicationDidEnterBackground event, I should start a task with beginBackgroundTaskWithExpirationHandler.

The problem is that, if I've understood correctly, this allows a maximum of 10/15 minutes after which the app is terminated if the task is not stopped with endBackgroundUpdateTask, while I want the task to keep polling the service indefinitely (at least until the user disable it from the app's settings)

My question is:

How is this kind of functionality performed normally? Do some common solutions or best practices exist for the solution of such a problem?

回答1:

Use iOS Background Fetch feature where you can specify minimum background fetch interval. But actual interval between successive invocation of your code will be determined by iOS framework. For details checkout this link: http://code.tutsplus.com/tutorials/ios-7-sdk-working-with-background-fetch--mobile-20520

I use this approach in my app and I think it is a preferred way of doing.



回答2:

  1. You can use a local notification that can be presented from the background in case your condition is met.

  2. Correct, iOS will eventually shut down the background process, you can't enforce continuous background activity. Use the backgroundTimeRemaining property to check how much time your application has left and try to handle it as gracefully as possible by calling endBackgroundTask so that iOS does not force kill your app.

As a solution, you could think about using remote notifications with with content-available : YES, which runs the didReceiveRemoteNotification



回答3:

Have a look at the Parse.com Their local datastore is an abstraction for what you are trying to acheive. By the way, is it really necessary to refresh in the background. If call is relatively quick, there is no need to refresh until the user open's the app. Background processes like that, using the net can be quite battery consuming when the user are not on a Wifi. So consider the use case carefully!