Background fetch performFetchWithCompletionHandler not working?

霸气de小男生 提交于 2021-01-29 10:34:19

问题


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

  1. I am unable to enter performFetchWithCompletionHandler method unless I click Debug>simulate background fetch
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!