ios - 将 BGTaskScheduler API 与新的 iOS 14 应用程序结合使用。如何在没有 AppDelegate 的情况下注册任务?

标签 ios swift swiftui ios14

我正在使用 BGTaskScheduler API 在我的 iOS 14 应用程序中注册后台任务,该应用程序使用新应用程序作为 @Main而不是 AppDelegate .我以为我们要使用 scenePhase如下所示,以模仿 AppDelegate 中 didFinishLaunching 的先前功能,但以下会导致崩溃:*** Assertion failure in -[BGTaskScheduler _unsafe_registerForTaskWithIdentifier:usingQueue:launchHandler:], BGTaskScheduler.m:185 2020-12-01 12:53:40.645091-0500 newFitnessApp[13487:1952133] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'All launch handlers must be registered before application finishes launching'如何实现BGTaskScheduler?

@main
struct newFitnessAppApp: App {
    
    @Environment(\.scenePhase) var scenePhase
    
    //Launch Count (for requesting reviews and to show tutorial)
    //var launchCount = UserDefaults.standard.integer(forKey: TrackerConstants.launchCountKey)
    //var testMode = true
    //@Environment(\.scenePhase) private var phase
    let trackerDataStore = TrackerDataStore(workoutLoader: HealthKitWorkoutLoader())
    
    var body: some Scene {
        WindowGroup {
            AppRootView().environmentObject(trackerDataStore)
        }
        .onChange(of: scenePhase) { newScenePhase in
            switch newScenePhase {
            case .active:
                print("App is active")
                registerBackgroundTasks()

最佳答案

尝试在init中执行

@main
struct newFitnessAppApp: App {

   init() {
      registerBackgroundTasks()
   }

// ... other code
}

或使用 AppDelegate 适配器在委托(delegate)回调中执行此操作 https://stackoverflow.com/a/62538373/12299030

关于ios - 将 BGTaskScheduler API 与新的 iOS 14 应用程序结合使用。如何在没有 AppDelegate 的情况下注册任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65096278/

相关文章:

ios - 将点击操作添加到 NavigationController 中的自定义 View

ios - Xcode 10 Storyboard不显示元素,只有蓝色边框

ios - UIImage(文件内容:) returning nil despite file existing in caches directory

ios - itms-app ://and https://App Store link 有什么区别

ios - 核心数据后台处理,保存不推送到主上下文

ios - 如何在 Swift 中使用带有 startIndex 和长度的 substringWithRange()

ios - GCM 推送通知返回错误消息 "GCM registration is not ready with auth credentials...."

swift - 更新 UIHostingConfiguration 中的@FocusState

ios - Swift UI 中的动画文本

swift - SwiftUI 中的 NavigationBarTitle 文本颜色