Kalyan
Kalyan

Reputation: 263

How to make URLSession to work when app is moved to background

On a button click, I have to implement multiple API calls to get the data and write that data to file. I am using Operation Queue and URLSession datatask to implement this. While this API calls are in process, If the app is placed to background either by clicking home button or by a phone call, then the API calls are not processing.

I tried Operation queue and as well Dispatch_async() functions, but nothing worked when the app is placed in the background after API calls are invoked.

API requests should even work when the app is placed in the background. How can this be achieved?

Upvotes: 3

Views: 4532

Answers (4)

jpulikkottil
jpulikkottil

Reputation: 686

If you are using datatask, then you can implement backgroundTask which well explained in https://medium.com/@abhimuralidharan/finite-length-tasks-in-background-ios-swift-60f2db4fa01b

If you are using DownloadTask or UploadTask , you can use the configuration

URLSessionConfiguration.background(withIdentifier:
                                   "com.yourapp.bundleidentifier")

Upvotes: 3

Komal Goyani
Komal Goyani

Reputation: 847

Add beginBackgroundTask in your AppDelegate class.

func applicationDidEnterBackground(_ application: UIApplication) {

    _ = UIApplication.shared.beginBackgroundTask(expirationHandler: {

    })
}

Upvotes: 1

Jarry
Jarry

Reputation: 31

try this UIApplication.shared.beginBackgroundTask(expirationHandler: { }) and its related API, hope it works for ya.

Upvotes: 0

rptwsthi
rptwsthi

Reputation: 10172

In order to make your application keep processing the information in the background, you need to update the configuration from default to:

let configuration = URLSessionConfiguration.background(withIdentifier:
                                   "com.yourapp.bundleidentifier")

You can have more detailed information about this on this very nice tutorial about URLSession.

Upvotes: 0

Related Questions