【问题标题】:BGTaskScheduler fails with no background task exists with identifier or it may have already been endedBGTaskScheduler 失败,不存在具有标识符的后台任务,或者它可能已经结束
【发布时间】:2020-05-26 23:58:22
【问题描述】:

使用 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()
 }


 }

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

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>ch.blah.refresh</string>
</array> 

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

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

【问题讨论】:

  • Apple 的一位同事告诉您可以忽略这一点?我可以这样做,但是当我运行它时我仍然什么也看不到?这是一个理智的操作吗?
  • 我相信这个错误是一个红鲱鱼(我在后台的多个项目中遇到相同的错误,没有不利影响);一些关于这里的讨论:forums.developer.apple.com/thread/121990 此外,代码可能很好,但在系统决定之前不会执行,如下所述:stackoverflow.com/questions/59454989/…
  • 我在模拟器上遇到了同样的问题。但我在装有 iOS 13.4 的 Real 设备上尝试过,它运行起来非常流畅。我也可以看到正在模拟的任务。 developer.apple.com/documentation/backgroundtasks/…

标签: ios swift ios13 swift5


【解决方案1】:

试试这个:

let queue = OperationQueue.main

【讨论】:

猜你喜欢
  • 2014-07-15
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多