WKExtension scheduleBackgroundRefreshWithPreferredDate 需要 WKExtensionDelegate 实现 handleBackgroundTasks 而不是 handle

WKExtension scheduleBackgroundRefreshWithPreferredDate requires WKExtensionDelegate to implement handleBackgroundTasks instead of handle

我正在为手表应用实现后台应用刷新。为了启动后台刷新,我在加载 ContentView 时在模型启动期间调用了以下函数:

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

然后我有我的 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)
            }
        }
    }

但是,应用程序崩溃了:

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

因此,需要实施handleBackgroundTasks。据我了解,handleBackgroundTasks 已重命名为 handle。因为 Xcode 13.2.1 抱怨如果我实现 handleBackgroundTasks 并且不编译:

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

有什么问题?

看来我需要为 SwiftUI 显式提供委托:

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

我在想只要写一个 class ExtensionDelegate 并在扩展的 Info.plist 中指定它就可以了。不会的。