Background URLSession
Background URLSession
Perform uploads and downloads that continue when your app is suspended using background URL sessions.
Configure Background Session
Create a background configuration with a unique identifier, then build a URLSession with a delegate.
Syntax:
URLSessionConfiguration.background(withIdentifier:)URLSession(configuration:delegate:delegateQueue:)
Example
import Foundation
final class BGSession: NSObject, URLSessionDownloadDelegate {
static let shared = BGSession()
lazy var session: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "com.example.bg")
config.isDiscretionary = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
// Move file from temporary location to a permanent URL
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Background URLSession Setup")
.padding()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example sets up a background session and implements a download delegate callback.
Start a Download or Upload
Use downloadTask for large file downloads and uploadTask with a file URL for uploads.
Syntax:
session.downloadTask(with: url).resume()session.uploadTask(with: request, fromFile: url).resume()
Example
import Foundation
func startDownload() {
let url = URL(string: "https://example.com/large.zip")!
BGSession.shared.session.downloadTask(with: url).resume()
}
func startUpload(file: URL) {
var req = URLRequest(url: URL(string: "https://example.com/upload")!)
req.httpMethod = "POST"
BGSession.shared.session.uploadTask(with: req, fromFile: file).resume()
}
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 12) {
Button("Start Download") { startDownload() }
Button("Start Upload") { /* pick file and call startUpload */ }
}
.padding()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example kicks off background-friendly download and upload tasks.
Handle Background Completion
iOS will relaunch your app to deliver background session events. Bridge the completion handler in your app delegate.
Syntax: application(_:handleEventsForBackgroundURLSession:completionHandler:)
Example
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
var bgCompletionHandler: (() -> Void)?
func application(_ application: UIApplication,
handleEventsForBackgroundURLSession identifier: String,
completionHandler: @escaping () -> Void) {
bgCompletionHandler = completionHandler
}
}
// Later, after URLSession finishes all events:
extension BGSession: URLSessionDelegate {
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
(UIApplication.shared.delegate as? AppDelegate)?.bgCompletionHandler?()
(UIApplication.shared.delegate as? AppDelegate)?.bgCompletionHandler = nil
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Handle Background Completion")
.padding()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example stores the system-provided completion handler and calls it when all background events are processed.
Tip: Provide a background session identifier and handle completion callbacks in the app delegate.