小编Dea*_*rae的帖子

BGAppRefreshTask 后台任务未执行

我正在使用新的 iOS13 后台任务框架,并实现了 BGAppRefreshTask 类型。我的问题是,我的设备从不调用任务,即使等待了几个小时,但我能够使用调用 _simulateLaunchForTaskWithIdentifier 的调试器技巧成功运行代码。

我已经设置了以下内容:

  • 使用后台模式功能启用我的应用程序,检查“后台获取”。
  • 在“允许的后台任务调度程序标识符”下将我的背景 ID 添加到 Info.plist:“com.XYZ.PearWeather.backgroundAlerts”。

我已经在我的 AppDelegate 中从 application(didFinishLaunchingWithOptions) 注册了任务:

        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.XYZ.PearWeather.backgroundAlerts", using: nil) { task in
            self.backgroundAlerts(task: task as! BGAppRefreshTask)
        }
Run Code Online (Sandbox Code Playgroud)

我正在 AppDelegate 内的 func 中调度任务,并从我的 SceneDelegate sceneDidEnterBackground() 调用它。它原本是一个静态的func,但我现在已经把它改成了一个实例func,并得到了AppDelegate实例(因为我在绝望中尝试了很多变化):

    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as! AppDelegate).scheduleBackgroundAlerts()
    }
Run Code Online (Sandbox Code Playgroud)
    func scheduleBackgroundAlerts() {
        let request = BGAppRefreshTaskRequest(identifier: "com.XYZ.PearWeather.backgroundAlerts")

        request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)

        do {
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: \(error)")
        }
    }
Run Code Online (Sandbox Code Playgroud)

至少在Debugger场景下,submit调用是没有错误的。我为上面的 timeIntervalSinceNow 参数尝试了许多不同的值。我还从任务处理程序本身调用了这个 scheduleBackgroundAlerts() …

background task ios swift

9
推荐指数
2
解决办法
2212
查看次数

标签 统计

background ×1

ios ×1

swift ×1

task ×1