How to register background tasks in a pure SwiftUI app

I'm creating a pure SwiftUI app. I wish to use a background task to keep my data up-to-date while in the background. I've found the BGTaskScheduler documentation (https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler). In the section titled Register, Schedule, and Run Tasks, the document states:

During app startup, you register a launch handler, a small block of code that runs the task, and an associated unique identifier for each task. Register all of the tasks before the end of the app launch sequence. For more information, see About the App Launch Sequence.

I know you can do this in application(_ :, didFinishLaunchingWithOptions:) method of the AppDelegate. However, in a pure SwiftUI app there is no AppDelegate. So, how do I register my background task in SwiftUI? If I can't, then how do a retrofit an AppDelegate into an already existing SwiftUI app?

Thanks, Alan

I am curious either.

You can register the task inside the init function of the App struct.

@main
struct MyApp: App {
    init(){
        // Your code
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Or, to use AppDelegate in a SwiftUI lifecycle app, first create a custom class of App Delegate.

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        return true
    }
}

Then use UIApplicationDelegateAdaptor property wrapper to tell SwiftUI to use your AppDelegate class.

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
How to register background tasks in a pure SwiftUI app
 
 
Q