blog.stackademic.com 3 min read Original Source

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 BGAppRefreshTask and BGProcessingTask
  • 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:

  1. BGAppRefreshTask
    –
    Lightweight tasks
  • Short runtime (~30 seconds)
  • Ideal for fetching updates or syncing small data
  • System runs it based on device conditions (power, usage)
  1. 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

  1. Go to your app target β†’ Signing & Capabilities
  2. Click the + Capability button
  3. 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️!