问题
My app want to update server about users location after every 5 seconds even if app is in background. I implemented Background fetch for it.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil))
application.setMinimumBackgroundFetchInterval(5.0)
return true
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.NewData)
UpdateData()
}
func UpdateData(){
print("UpdateData executes")
// function to update data when ever this method triggers
}
but the problem is
- I am unable to enter performFetchWithCompletionHandler method unless I click Debug>simulate background fetch
- How can I achieve to invoke performFetchWithCompletionHandler after every 5 seconds.
回答1:
You have a misunderstanding about what background fetch is. Developers have no power over when a background fetch will be performed exactly. iOS itself decides when to allow an app to perform a background fetch.
The setMinimumBackgroundFetchInterval
function only allows you to specify a minimum time interval that has to pass between background fetches to minimize the energy and data usage of your app. However, the interval you set here does not guarantee at all that your app will be able to perform a background fetch this frequently. The key sentence in the documentation regarding this is "Fetch content opportunistically in the background...".
At the moment, the only way to ensure that your app can execute certain functions (including fetching data from a server) in the background is by sending silent push notifications from your own server at regular intervals. However, even then, the system might decide not to wake up your app in response to a silent push notification if your app takes to long to finish execution in response to the push or if your app receives too many notifications.
来源:https://stackoverflow.com/questions/50375733/background-fetch-performfetchwithcompletionhandler-not-working