Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Background App Refresh

Hi, I have a couple questions about background app refresh. First, is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background? Second, despite importing BackgroundTasks, I am getting the error "cannot find operationQueue in scope". What can I do to resolve that? Thank you.

func scheduleAppRefresh() {
       let request = BGAppRefreshTaskRequest(identifier: "peaceofmindmentalhealth.RoutineRefresh")
       // Fetch no earlier than 15 minutes from now.
       request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
            
       do {
          try BGTaskScheduler.shared.submit(request)
       } catch {
          print("Could not schedule app refresh: \(error)")
       }
    }
    
    func handleAppRefresh(task: BGAppRefreshTask) {
       // Schedule a new refresh task.
       scheduleAppRefresh()


       // Create an operation that performs the main part of the background task.
       let operation = RefreshAppContentsOperation()
       
       // Provide the background task with an expiration handler that cancels the operation.
       task.expirationHandler = {
          operation.cancel()
       }


       // Inform the system that the background task is complete
       // when the operation completes.
       operation.completionBlock = {
          task.setTaskCompleted(success: !operation.isCancelled)
       }


       // Start the operation.
       operationQueue.addOperation(operation)
     }
    
    func RefreshAppContentsOperation() -> Operation {
        
    }
Answered by DTS Engineer in 841458022

Indeed. I guess I should be able to recognise our own documentation code )-:

Anyway, with that context, I can answer your specific questions:

is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background?

Yes and no. In this example RefreshAppContentsOperation is meant to be an Operation subclass that implements the app refresh operation. If you want to use this approach, you’d create your own subclass of Operation and then implement the main() method on that. For example:

final class RefreshAppContentsOperation: Operation {
    override func main() {
        … your code here …
    }
}

However, there are other approaches you might adopt. For example, you might start a Task and run Swift async code within that task.

Note The term task is overloaded in this context. The Background Tasks framework uses it to refer to the state that’s tracking the work and Swift concurrency uses it to refer to the state of the code that’s actually doing the work.

I am getting the error “cannot find operationQueue in scope”

Right. That’s because the doc assumes that you’re using Operation to managed this work. If you were doing that then you would have an operation queue lying around. If you’re not, then you have a choice:

  • You can use Operation as assumed by the doc. In that case, you’d need to create your own operation queue and supply it in the place of operationQueue.

  • You can use some other mechanism, in which case you won’t need an operation queue at all. For example, in Swift concurrency you can start a Task without worrying about where it starts (Swift concurrency has the concept of a global executor that runs tasks by default).

Historically, I was a big fan of Operation and I’d use it all the time for stuff like this. These days, however, I’d definitely do this work with Swift concurrency.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

You seem to be following some sort of tutorial or sample. Can you post a link to that? Because it’s hard to answer your questions without understanding that context. For example, you’ve decided to use an Operation to handle the request, but there’s no requirement to do that in the API, and so it’s hard to describe what’s up with operationQueue without that context.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Indeed. I guess I should be able to recognise our own documentation code )-:

Anyway, with that context, I can answer your specific questions:

is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background?

Yes and no. In this example RefreshAppContentsOperation is meant to be an Operation subclass that implements the app refresh operation. If you want to use this approach, you’d create your own subclass of Operation and then implement the main() method on that. For example:

final class RefreshAppContentsOperation: Operation {
    override func main() {
        … your code here …
    }
}

However, there are other approaches you might adopt. For example, you might start a Task and run Swift async code within that task.

Note The term task is overloaded in this context. The Background Tasks framework uses it to refer to the state that’s tracking the work and Swift concurrency uses it to refer to the state of the code that’s actually doing the work.

I am getting the error “cannot find operationQueue in scope”

Right. That’s because the doc assumes that you’re using Operation to managed this work. If you were doing that then you would have an operation queue lying around. If you’re not, then you have a choice:

  • You can use Operation as assumed by the doc. In that case, you’d need to create your own operation queue and supply it in the place of operationQueue.

  • You can use some other mechanism, in which case you won’t need an operation queue at all. For example, in Swift concurrency you can start a Task without worrying about where it starts (Swift concurrency has the concept of a global executor that runs tasks by default).

Historically, I was a big fan of Operation and I’d use it all the time for stuff like this. These days, however, I’d definitely do this work with Swift concurrency.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I have the following code in ContentView:

.onAppear {
            BGTaskScheduler.shared.register(forTaskWithIdentifier: "appname.RoutineRefresh", using: nil) { task in
     print(task)
                
     handleAppRefresh(task: task as! BGAppRefreshTask)
  }
}

However, nothing prints. Additionally, I have print statements in scheduleAppRefresh and handleAppRefresh but nothing prints from those functions either.

I am also calling scheduleTaskRefresh in a .task function.

My general advice on this front is not to to do any of this work at the view level. Rather, this work should be done somewhere down in the model layer. So, it’s fine for activity in your UI to inform your model that it’s currently on screen and thus should try to update if possible, but all the update logic should be in your model. And, critically, these updates just change your model and your view responds to those changes in the same way it responds to any other changes.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Could you elaborate on how to build a model layer and how that differentiates from calling a function from a .task or .onappear function within the view level? What do I need to pass to handleAppRefresh?

import Foundation
import SwiftData
import SwiftUI
import BackgroundTasks

func scheduleAppRefresh() {
   let request = BGAppRefreshTaskRequest(identifier: "app.RoutineRefresh")
   // Fetch no earlier than 15 minutes from now.
   request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
        
   do {
      try BGTaskScheduler.shared.submit(request)
   } catch {
      print("Could not schedule app refresh: \(error)")
   }
}

func handleAppRefresh(task: BGAppRefreshTask) async {
   // Schedule a new refresh task.
   scheduleAppRefresh()


   // Create an operation that performs the main part of the background task.
   let operation = RefreshAppContentsOperation()
   
   // Provide the background task with an expiration handler that cancels the operation.
   task.expirationHandler = {
      operation.cancel()
   }


   // Inform the system that the background task is complete
   // when the operation completes.
   operation.completionBlock = {
      task.setTaskCompleted(success: !operation.isCancelled)
   }


   // Start the operation.
   //operationQueue.addOperation(operation)
 }


final class RefreshAppContentsOperation: Operation, @unchecked Sendable {
    @Environment(\.modelContext) private var modelContext
    
    override func main() {
        
    }
}
Could you elaborate on how to build a model layer … ?

Sure.

My preference is to have a passive model to which you can apply changes. The views can then observe the model and update accordingly. Then operations in the views result in changes to the model, which results in a one-way circular data flow: Views change the model and then react to changes in the model. So, you start with an architecture like this:

views
^   |
|   v
model

With that architecture, the views don’t have to be the only thing changing the model. You can, for example, build networking code that changes the model and the views then update to reflect those changes. The views don’t care that the change came from the network, they just update. So, adding your networking code results in this:

views
^   |
|   v
model <- network

In this diagram, the network item is often called a controller, although opinions differ as to whether that’s a correct use of that term.

Anyway, the point of this is that the views should never be in the business of dealing with the network. They are just about displaying the model. This allows makes it easy to test the views, display them in previews, and so on.

In this architecture, the business of app refresh doesn’t involve the views at all. Rather, you’d create another controller-y thing that manages the app refresh work and passes those instructions on to network. So, something like this:

views    refresh
^   |       |
|   v       v
model <- network

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Okay, thank you. And just clarifying, what needs to be passed to the handleAppRefresh function?

In the original article you referenced, handleAppRefresh(task:) is a function that you create and call in your BGTaskScheduler launch handler. It has two aspects:

  • It acts as a placeholder for whatever code you need to update your model.

  • It takes care of the ‘bookkeeping’ required by BGAppRefreshTask.

I can’t offer specific advice about the first aspect. That work is very much dependent on your model, your networking layer, and so on.

With regards the second aspect, that bookkeeping involves:

  • Calling setTaskCompleted(success:) when the update work completes.

  • Setting the expiration handler (expirationHandler) on the task, and making sure to cancel your update work if it expires.

  • Scheduling a subsequent app refresh task, if you determine one is necessary.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

With the code below I get the error:

class BackgroundTasksController: ObservableObject {
    func scheduleRoutineResetTask() {
        Task {
            BGTaskScheduler.shared.register(forTaskWithIdentifier: "app.BackgroundTask", using: nil) { task in
                Task {
                    await self.handleAppRefresh(task: task as! BGAppRefreshTask)
                }
            }
        }
    }
    
    private func handleAppRefresh(task: BGAppRefreshTask) async {
       // Schedule a new refresh task.
       scheduleAppRefresh()
        
       // Create an operation that performs the main part of the background task.
       let operation = RefreshAppContentsOperation()
       
       // Provide the background task with an expiration handler that cancels the operation.
       task.expirationHandler = {
          operation.cancel()
       }


       // Inform the system that the background task is complete
       // when the operation completes.
       operation.completionBlock = {
          task.setTaskCompleted(success: !operation.isCancelled)
       }


       // Start the operation.
       //operationQueue.addOperation(operation)
     }
    
    
    
    private func scheduleAppRefresh() {
       let request = BGAppRefreshTaskRequest(identifier: "app.BackgroundTask")
       // Fetch no earlier than 15 minutes from now.
       request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
        
        print(request)
            
       do {
          try BGTaskScheduler.shared.submit(request)
       } catch {
          print("Could not schedule app refresh: \(error)")
       }
    }

}


final class RefreshAppContentsOperation: Operation, @unchecked Sendable {
    
}

*** Assertion failure in -[BGTaskScheduler _unsafe_registerForTaskWithIdentifier:usingQueue:launchHandler:], BGTaskScheduler.m:225 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'All launch handlers must be registered before application finishes launching' *** First throw call stack: (0x18b5d321c 0x188a6dabc 0x18a8d1670 0x224da17f0 0x224da15f0 0x102fee124 0x102fee24d 0x102fefe1d 0x102feff79 0x19709d241) libc++abi: terminating due to uncaught exception of type NSException *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'All launch handlers must be registered before application finishes launching' *** First throw call stack: (0x18b5d321c 0x188a6dabc 0x18a8d1670 0x224da17f0 0x224da15f0 0x102fee124 0x102fee24d 0x102fefe1d 0x102feff79 0x19709d241) terminating due to uncaught exception of type NSException

Is this configuration proper, and with this configuration is.addOperation necessary?

Background App Refresh
 
 
Q