7

I am testing and debugging the expiration block in - beginBackgroundTaskWithExpirationHandler:.

Is there a way to force the Block call so that it happens quicker, instead of waiting for about 10 minutes each time I need to debug it?

I am not interested in debugging the actual code in the block, rather I am interested in the sequence of calls and the backtrace, etc.; that's why I need the callback itself to happen, but 10 minutes each time is too long!

jscs
  • 63,694
  • 13
  • 151
  • 195
Sierra Alpha
  • 3,707
  • 4
  • 23
  • 36

2 Answers2

0

Emulating the expiration of the background task time:

  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 can be known by testing when the expiration handler is triggered. because the backgroundTimeRemaining is not guaranteed to be accurate.

Code:

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
    }
}
hasan
  • 23,815
  • 10
  • 63
  • 101
-2

If you are looking to force the system to call the expiration block, I don't think that can be done. However, I would suggest that you isolate your background task block, then call it using a NSTimer or

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

At least thats how I would do it.

Meaning, that you would call the code in your expiration handler directly using a NSTimer (implied or explicitly). So, if in your expiration handler you called a method that handled the expiration. Then, you would set a timer for that method to be called outside of the "background task" lifecycle, but you would be only simulating it.

C. Bess
  • 567
  • 7
  • 10