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

BackgroundSession.swift

ContentView.swift

App.swift

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
} }

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

StartTasks.swift

ContentView.swift

App.swift

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()
}

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

AppDelegate.swift

ContentView.swift

App.swift

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
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *