How to keep API requests running in background using URLSession in Swift?

I'm developing an iOS application in Swift that performs API calls using URLSession.shared. The requests work correctly when the app is in the foreground. However, when the app transitions to the background (for example, when the user switches to another app), the ongoing API calls are either paused or do not complete as expected.

What I’ve tried: Using URLSession.shared.dataTask(with:) to initiate the API requests

Observing application lifecycle events like applicationDidEnterBackground, but haven't found a reliable solution to allow requests to complete when backgrounded

Goal: I want certain API requests to continue running or be allowed to complete even if the app enters the background.

Question: What is the correct approach to allow API calls to continue running or complete when the app moves to the background? Should I be using a background URLSessionConfiguration instead of URLSession.shared? If so, how should it be properly configured and used in this scenario?

Answered by DTS Engineer in 862982022

IMO it’s best to classify your requests into two groups:

  • Small, interactive requests
  • Large transfers

Use a background session for the latter. The system will then continue to process the request even if your app is suspended in the background.

Use a standard session for your small, interactive requests. You then have two options:

  • Cancel any outstanding request as the app moves to the background.
  • Use a UIApplication background task to prevent your app from being suspended in the background while the request is in flight.

See UIApplication Background Task Notes for more info about that last bit.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

IMO it’s best to classify your requests into two groups:

  • Small, interactive requests
  • Large transfers

Use a background session for the latter. The system will then continue to process the request even if your app is suspended in the background.

Use a standard session for your small, interactive requests. You then have two options:

  • Cancel any outstanding request as the app moves to the background.
  • Use a UIApplication background task to prevent your app from being suspended in the background while the request is in flight.

See UIApplication Background Task Notes for more info about that last bit.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to keep API requests running in background using URLSession in Swift?
 
 
Q