iosswiftbackgroundurlsessionnsurlsessiondatatask

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?


Solution

  • 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")