Search code examples
iosobjective-ccocoa-touchmultitaskingnsoperationqueue

How can I extend an NSOperationQueue with dependencies for appDidEnterBackground?


I know how to extend a task for running in the background after an iOS app enters background with

beginBackgroundTaskWithExpirationHandler
dispatch_async

etc.

But what if I have an NSOperationQueue that I want to extend as background tasks, without losing the interdependencies of the NSOperations? Say I have this:

NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
    // Do stuff
}];

NSBlockOperation *op2a = [NSBlockOperation blockOperationWithBlock:^{
    // Do stuff
}];
[op2a addDependency:op1];

NSBlockOperation *op2b = [NSBlockOperation blockOperationWithBlock:^{
    // Do stuff
}];
[op2b addDependency:op1];

NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
    // Do stuff
}];
[op3 addDependency:op2a];
[op3 addDependency:op2b];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperations: @[op1, op2a, op2b, op3] ];

Is there an elegant way to have the NSOperationQueue finish in the background?


Solution

  • I realized that I didn't fully understand how background thread extension works.

    After calling beginBackgroundTaskWithExpirationHandler to start the background extension, I can do whatever I want in the background. I thought there is just one thread extended, but it's in fact the whole application that keeps running.

    Therefore I just have to call endBackgroundTask at the end of the last NSOperation to achieve what I want.