1

I wanted to download data in background even when app is not running. Is it possible? I have tried using background fetch but it is not working. Please refer to the code below:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    UIApplication.shared.applicationIconBadgeNumber = 9
}

It gets called when app is running but not when app is killed

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
  • If the user terminates your app then it doesnt execute until the user relaunches it (there is an exception for VoIP push and location geofence entry). – Paulw11 May 22 '17 at 13:10
  • 1
    Possible duplicate of [Will iOS launch my app into the background if it was force-quit by the user?](https://stackoverflow.com/questions/19068762/will-ios-launch-my-app-into-the-background-if-it-was-force-quit-by-the-user) – Scriptable May 22 '17 at 14:22
  • See https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623013-application#discussion. which states: However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again. – Scriptable May 22 '17 at 14:23

1 Answers1

0

Unfortunately background fetch works for max 3 min after the app is deactivated or in the background. Except for VOIP, Location, Audio..ect

What you can do is send a remote push notification "according to a certain event taking place in your backend server" to your App so the user interacts with it and gets your app to the foreground.

As soon as the app is loaded to the foreground you can add an observer with a selector function in viewWillAppear to start fetching the data you need.

NotificationCenter.default.addObserver(self, selector:#selector(applicationWillEnterForeground(_:)), name:NSNotification.Name.UIApplicationWillEnterForeground, object: nil)

Selector function:

func applicationWillEnterForeground(_ notification: NSNotification) {

    print("Fetch data")

}

Then in viewWillDisappear remove the observer:

NotificationCenter.default.removeObserver(self)
Kegham K.
  • 1,589
  • 22
  • 40