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)
| 归档时间: |
|
| 查看次数: |
4834 次 |
| 最近记录: |