Background Modes & Tasks
Background Modes & Tasks
Declare the right background modes and schedule work with BGTaskScheduler for refresh or processing tasks.
Enable Background Modes
In Signing & Capabilities, add Background Modes.
Check the modes you need (e.g., Background fetch, Background processing, Location updates, Audio, VOIP).
Background Tasks (BGTaskScheduler)
Use BGAppRefreshTask or BGProcessingTask to schedule work when your app is not active.
Example
import BackgroundTasks
let refreshTaskID = "com.example.myapp.refresh"
func scheduleRefresh() {
let request = BGAppRefreshTaskRequest(identifier: refreshTaskID)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
try? BGTaskScheduler.shared.submit(request)
}
func handleRefresh(task: BGAppRefreshTask) {
scheduleRefresh() // reschedule
task.expirationHandler = { /* cancel work */ }
// Do lightweight refresh work here
task.setTaskCompleted(success: true)
}
import SwiftUI
import BackgroundTasks
@main
struct MyApp: App {
init() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.myapp.refresh", using: nil) { task in
if let t = task as? BGAppRefreshTask { handleRefresh(task: t) }
}
}
var body: some Scene { WindowGroup { ContentView() } }
}
This example schedules a BGAppRefreshTask, registers a handler at app start, and marks the task completed after lightweight work.
Tip: Background execution is constrained.
Keep work short, declare only necessary modes, and test in the Background Tasks debugger.