BGTaskScheduler 失败,不存在带有标识符的后台任务,或者它可能已结束

use*_*232 5 ios swift swift5 ios13

使用 iOS 13.3.1 Xcode 11.3.1 Swift 5

代码是这样说的,可以编译但不能正确运行。当我在后台运行我的应用程序时,我收到一条错误消息,显示“由于不存在标识符为 1 的后台任务而失败,或者它可能已结束”。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
BGTaskScheduler.shared.register(forTaskWithIdentifier: "ch.blah.refresh", using: nil) { (task) in
  self.handleAppRefresh(task: task as! BGAppRefreshTask)
}


return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
  scheduleAppRefresh()
}

var request: BGAppRefreshTaskRequest!

func scheduleAppRefresh() {
  request = BGAppRefreshTaskRequest(identifier: "ch.blah.refresh")
  request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
do {
  try BGTaskScheduler.shared.submit(request)
} catch {
  print("Could not schedule app refresh: \(error)")
}

}

func handleAppRefresh(task: BGAppRefreshTask) {
 scheduleAppRefresh()

 let queue = OperationQueue()
 queue.maxConcurrentOperationCount = 1

 queue.addOperation {
   for i in 1 ... 1000000 {
    print("\(i)")
   }
 }

 let lastOp = queue.operations.last
 lastOp?.completionBlock = {
   task.setTaskCompleted(success: !lastOp!.isCancelled)
 }

 task.expirationHandler = {
   queue.cancelAllOperations()
 }


 }
Run Code Online (Sandbox Code Playgroud)

是的,我确实将密钥添加到了 Info.plist

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>ch.blah.refresh</string>
</array> 
Run Code Online (Sandbox Code Playgroud)

由于 iOS 13,我遇到了几次失败。我错过了什么?

我确实尝试下载 Apple WWDC 代码来查看。但它似乎也有同样的问题。

小智 1

尝试这个:

let queue = OperationQueue.main
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码可以回答问题,但提供有关此代码为何和/或如何回答问题的附加上下文可以提高其长期价值。考虑阅读[如何回答](https://stackoverflow.com/help/how-to-answer)并[编辑]您的答案以改进它。 (3认同)