我正在测试和调试 - beginBackgroundTaskWithExpirationHandler:
中的过期 block 。
有没有办法强制调用 Block 以使其更快发生,而不是每次我需要调试时都等待大约 10 分钟?
我对调试 block 中的实际代码不感兴趣,而是对调用顺序和回溯等感兴趣;这就是为什么我需要回调本身发生,但每次 10 分钟太长了!
最佳答案
模拟后台任务时间到期:
- Start your background task on controller
viewDidLoad
and Schedule aTimer
that prints out thebackgroundTimeRemaining
every 1 second.- Send your app to background.
- Trigger the action of your background task when the
backgroundTimeRemaining
is less than X seconds.
可以通过测试何时触发过期处理程序来获知 X。因为不保证 backgroundTimeRemaining 是准确的。
代码:
UIApplication.shared.beginBackgroundTask(withName: "Submit Order Background Task") { [weak self] in
// Your logic to handle the expiration.
}
// To submit order 1 time!
var submitted = false
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
print("background task timer: \(UIApplication.shared.backgroundTimeRemaining)")
if UIApplication.shared.backgroundTimeRemaining < 2 && !submitted {
self.submitOrder()
submitted = true
}
}
关于ios - 强制提前调用 iOS 设备上的后台任务到期处理程序以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18109713/