Run HTTP requests in the background

Viewed 274

In my app, I need to send a sequence of 4 requests. Requests need to be sent in order one after another.

  • Request 1 - regular HTTP POST request to the backend
  • Request 2 - file upload
  • Request 3 - file upload
  • Request 4 - regular HTTP POST request to the backend

This sequence needs to work in the background. I know that on iOS there's URLSession.uploadTask method that allows uploading files in the background.

Let's say that the user starts the sequence of requests, and then background the app right away.

  1. Can I make regular HTTP requests using URLSession.uploadTask method?
  2. When URLSession.uploadTask will finish while the app is in the background and the delegate method

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)

will be invoked, can I start another URLSession.uploadTask inside this delegate method, so that all 4 requests will be run in the background?

  1. Is URLSession.uploadTask the right approach to run all 4 requests in the background?
2 Answers

I will answer your all questions. But, firstly I choosed last.

  • 3-right approach to run all 4 requests in the background
  • Yes, you can do with this way but It's missing some details. For instance; you start your requests sequentially, and after that your app goes to background. But for a while, if the user kill app. What will do for this scenario?

  • 2-delegate method will catch in the background mode
  • AnswerYou can proceed your request in background mode, and yes delegate methods will get any state changes.

  • 1-Can I make regular HTTP requests using URLSession.uploadTask method?
  • AnswerActually I prefer AFNetworking SDK for this issue. I think, below topics will hep you to solve this issue.

    • BGAppRefreshTask: An object representing a short task typically used to refresh content that’s run while the app is in the background. Apple Document
    • Updating Your App with Background App Refresh

Calling the completion handler in a timely manner, and with an accurate result, helps determine how much future execution time your app receives. If you take too long to update your app, the system may schedule your app less frequently in the future to save power.

First, I would say you need to go to project settings, select your target, go to Signing and Capabilities and activate Background fetch and Background processing.

About the method to run the HTTP requests in the background, you can use that method or others. I personally recommend using Alamofire since it's the standard and has many features to expand your network layer in the future.

And yes, the delegate methods will still be executed in the background, after completion. Make sure to set the delegate variable.

Related