ios - 强制提前调用 iOS 设备上的后台任务到期处理程序以进行测试

标签 ios objective-c cocoa-touch background-process uiapplicationdelegate

我正在测试和调试 - beginBackgroundTaskWithExpirationHandler: 中的过期 block 。

有没有办法强制调用 Block 以使其更快发生,而不是每次我需要调试时都等待大约 10 分钟?

我对调试 block 中的实际代码不感兴趣,而是对调用顺序和回溯等感兴趣;这就是为什么我需要回调本身发生,但每次 10 分钟太长了!

最佳答案

模拟后台任务时间到期:

  1. Start your background task on controller viewDidLoad and Schedule a Timer that prints out the backgroundTimeRemaining every 1 second.
  2. Send your app to background.
  3. 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/

相关文章:

ios - UIDynamicAnimator,removeAllBehaviors() 第一次不起作用

ios - 使用 ios webView 播放视频时不调用 didEndDisplayingCell

ios - 延迟 IBAction 按钮

ios - 使用AV Foundation时捕获的图像方向错误

iphone - 如何将 iPhone 主屏幕捕获为图像?

cocoa-touch - 当我们可以写[NSString new]时,为什么我们有[NSString string]?

iphone - 跨 iPhone 和 Android 应用程序版本使用 Java 库

ios - 如何以编程方式使用 swift 在 iOS 应用程序中添加选项列表?

objective-c - 如何更改 NSPopupButton 的背景颜色?

iphone - 将多个文件复制到文档目录