Demo.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
}
}
import SwiftUI
import Foundation
struct ContentView: View {
var body: some View {
VStack(spacing: 12) {
Text("Background Session Config")
Button("Start sample download") {
let url = URL(string: "https://example.com/file.dat")!
BGSession.shared.session.downloadTask(with: url).resume()
}
}
.padding()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}