Cannot schedule background tasks in SwiftUI-based Watch app

How do I schedule a background task in my SwiftUI-based Watch app? When I call the following method:

WKApplication.shared()
    .scheduleBackgroundRefresh(
        withPreferredDate: Date.init(timeIntervalSinceNow: 15.0 * 60.0),
        userInfo: "MY_FIRST_UPDATE" as NSSecureCoding & NSObjectProtocol) { error in
            if error != nil {
                // Handle the scheduling error.
                fatalError("*** An error occurred while scheduling the background refresh task. ***")
            }

            print("*** Scheduled! ***")
        }

the app crashes:

2023-06-21 16:04:48.730140+0900 MyWatchApp[416:109084] [default] -[WKApplication scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:]:131: Critical failure. Simulating crash: Condition failed:"NO". -[WKApplication scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:] requires that your WKApplicationDelegate (null) implement handleBackgroundTasks:

My app is defined as follows:

@main
struct MyWatchApp: App {
    
    @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
    
    @StateObject var viewModel = MainViewModel.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                ... // bunch of stuff here
        }
        .backgroundTask(.appRefresh) { context in
            // I want to perform background task here
            await viewModel.handleBackgroundRefresh()
        }
    }
}

class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {
        ...
    }

    func applicationDidBecomeActive() {
        ...
    }

    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        // just in case, though this is not helping...
    }
}

I'm just following your instructions here:

https://developer.apple.com/documentation/watchkit/background_execution/using_background_tasks

Do I need to put some entry in my Info.plist? Or any capability I need to add? (I've added "Background Modes" with "Remote notifications" checked because I'm using CloudKit)

Any help is very much appreciated!

Replies

Apparently this was my mistake. I was calling WKApplication.shared().scheduleBackgroundRefresh() in MainViewModel.init(), but if I call it in applicationDidBecomeActive(), everything seems to be working!