iosswiftlocationbackground-fetchbackground-mode

Background fetch performFetchWithCompletionHandler not working?


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.

Solution

  • 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.