iOS Background Tasks: Everything You Need to Know (Swift 6)
π Introduction
Running code when your app is in the background β or even when it’s terminated β is one of the most powerful (and misunderstood) features of iOS. From syncing data, uploading files, and scheduling refresh tasks, to executing long operations, background tasks can dramatically improve user experience and app reliability.
In this post, we’ll dive deep into Apple’s BGTaskScheduler frameworkβavailable from iOS 13+, fully supported in iOS 17+βwith Swift 6-style code and real use cases.
By the end of this story, you’ll be able to:
- Schedule background refresh and processing tasks
- Understand the difference between
BGAppRefreshTaskandBGProcessingTask - Implement your background task handler
- Stay within iOS background execution limits
- Work with the latest async/await patterns in Swift
π Why Use Background Tasks?
Imagine building an app that:
- Pulls new content while the user is away (RSS reader, social media app)
- Uploads or syncs notes to iCloud or your server (notes, journals)
- Cleans up cache or does long-running maintenance (AI inference, video processing)
Background tasks let you do these things efficiently, respectfully, and in a battery-safe way.
π Key Concepts
There are two types of background tasks you can schedule using BGTaskScheduler:
- BGAppRefreshTask
– Lightweight tasks
- Short runtime (~30 seconds)
- Ideal for fetching updates or syncing small data
- System runs it based on device conditions (power, usage)
- BGProcessingTask
– For heavier tasks
- May require Wi-Fi and charging
- Can run for minutes
- Good for syncing files, uploading media, or ML inference
π¦ Project Setup: Enable Background Modes
- Go to your app target β Signing & Capabilities
- Click the + Capability button
- Enable Background Modes and check:
β Background fetch
β Background processing
Then, in your Info.plist, add:
<button data-code="BGTaskSchedulerPermittedIdentifiers
com.yourapp.refresh
com.yourapp.process
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.yourapp.refresh</string>
<string>com.yourapp.process</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.yourapp.refresh</string>
<string>com.yourapp.process</string>
</array>
β Step 1: Register the Background Tasks
Call this inside application(_:didFinishLaunchingWithOptions:) in AppDelegate:
import BackgroundTasks
func registerBackgroundTasks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.refresh", using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.process", using: nil) { task in
self.handleProcessing(task: task as! BGProcessingTask)
}
}
import BackgroundTasks
func registerBackgroundTasks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.refresh", using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.process", using: nil) { task in
self.handleProcessing(task: task as! BGProcessingTask)
}
}
β Step 2: Schedule Tasks
This could be triggered when the app goes into the background or on demand:
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.refresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes later
try? BGTaskScheduler.shared.submit(request)
}
func scheduleProcessingTask() {
let request = BGProcessingTaskRequest(identifier: "com.yourapp.process")
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false
try? BGTaskScheduler.shared.submit(request)
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.refresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes later
try? BGTaskScheduler.shared.submit(request)
}
func scheduleProcessingTask() {
let request = BGProcessingTaskRequest(identifier: "com.yourapp.process")
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false
try? BGTaskScheduler.shared.submit(request)
}
β Step 3: Handle Task Execution
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh() // Re-schedule for future
Task {
await refreshAppData()
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
}
func handleProcessing(task: BGProcessingTask) {
scheduleProcessingTask() // Re-schedule
Task {
await uploadPendingFiles()
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
}
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh() // Re-schedule for future
Task {
await refreshAppData()
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
}
func handleProcessing(task: BGProcessingTask) {
scheduleProcessingTask() // Re-schedule
Task {
await uploadPendingFiles()
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
}
π§ Example Task Methods
func refreshAppData() async {
// Example: Pull latest articles from your backend
print("π₯ Background refresh triggered")
try? await Task.sleep(for: .seconds(5))
}
func uploadPendingFiles() async {
// Example: Upload offline notes, media, or logs
print("π€ Uploading background files")
try? await Task.sleep(for: .seconds(10))
}
func refreshAppData() async {
// Example: Pull latest articles from your backend
print("π₯ Background refresh triggered")
try? await Task.sleep(for: .seconds(5))
}
func uploadPendingFiles() async {
// Example: Upload offline notes, media, or logs
print("π€ Uploading background files")
try? await Task.sleep(for: .seconds(10))
}
π± Testing Background Tasks
Use Xcode’s Debug > Simulate Background Fetch and simulate conditions via terminal:
xcrun simctl bgactivity trigger com.yourapp.refresh
xcrun simctl bgactivity trigger com.yourapp.refresh
Or test on device by sending app to background and waiting 15+ minutes.
π§ Limitations and Notes
- The system does not guarantee exact execution time
- Use
earliestBeginDateBut the system may delay it - Do not expect fast real-time sync (use silent push notifications for that)
- Always re-schedule the task after it runs, or it won’t repeat
β Summary
BGAppRefresh:
- β³ Duration: ~30 seconds
- π Charging Required: β
- πΆ Wi-Fi Required: β
- β Ideal For: Sync, refresh
BGProcessing:
- β³ Duration: Minutes
- π Charging Required: Optional β
- πΆ Wi-Fi Required: Optional β
- β Ideal For: Uploads, ML, cleanup
π§© Coming Up Next (Part 2)
In Part 2, we’ll dive into background uploads using URLSessionConfiguration.background, enabling you to upload media even if the app is killed.
π¬ Follow me for more practical iOS insights, SwiftUI, and Swift content.
Want help writing background sync logic or integrating push notifications? Drop your questions in the comments!
A message from our Founder
Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.
Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community. β€οΈ
If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, Instagram. You can also subscribe to our weekly newsletter.
And before you go, don’t forget to clap and follow the writerοΈ!
