Ad

WKExtension ScheduleBackgroundRefreshWithPreferredDate Requires WKExtensionDelegate To Implement HandleBackgroundTasks Instead Of Handle

- 1 answer

I'm implementing a background app refresh for a watch app. To initiate the background refresh, I call the function below during my model initiation when ContentView is loaded:

WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil)

Then I have my ExtensionDelegate:

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var backgroundURLTask: WKURLSessionRefreshBackgroundTask?
    
    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task in backgroundTasks {
            switch task {
                
            case let bgTask as WKApplicationRefreshBackgroundTask:
                ExtensionDelegate.scheduleNextAppBackgroundRefresh()
                let session = backgroundSession()
                // running a download task with the session
                
                bgTask.setTaskCompletedWithSnapshot(false)
                
            case let bgTask as WKURLSessionRefreshBackgroundTask:
                _ = backgroundSession()
                backgroundURLTask = bgTask
                
            case let bgTask as WKSnapshotRefreshBackgroundTask:
                bgTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.now.nextHourDate, userInfo: nil)
                
            default:
                task.setTaskCompletedWithSnapshot(false)
            }
        }
    }

However, the app crashes with:

WatchKit Extension[53878:533420] [bg_app_refresh] -[WKExtension scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:]:196: This call requires that your WKExtensionDelegate <SwiftUI.ExtensionDelegate: 0x6000039e5340> implement handleBackgroundTasks

So, it requires to implement handleBackgroundTasks. As I understand, handleBackgroundTasks was renamed to handle. Because Xcode 13.2.1 complains if I implement handleBackgroundTasks and doesn't compile:

handleBackgroundTasks' has been renamed to 'handle(_:)'

What's the problem with?

Ad

Answer

It appeared that I needed to provide the delegate for SwiftUI explicitly:

@main
struct MyApp: App {
    @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
    
    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}

I was thinking that just writing a class ExtensionDelegate and specifying it in the extension's Info.plist would work. It wouldn't.

Ad
source: stackoverflow.com
Ad