nothirst/TICoreDataSync — pull request #41 by ChronicStim (2013-04-02 17:24:17+00:00)
Title: Allowing for Continued Operation Processing After App Enters Background State

I'm going to submit a pull request for a possible approach to deal with this issue. Michael, it's similar to your suggestion, but I think assigning the task id at the point that the app is backgrounding is too late. Your code seems to wait for the backgrounding to happen and then you create a task to synchronize in the background. That's fine, and maybe even a good time to run a sync, but not my main concern.

I'm more concerned with the operations that are already running when the app is interrupted. Let's say we are in the middle of a whole store download or a synchronization process is already processing. In the current code, those operations will be killed after the 5 sec time limit when the app goes into the background state. There is also no clean way to cancel those ops that I could see (other than the "cancelSynchronization" method).

So, our approach was to add 2 properties to each of the sync managers and the generic operation class. One property is a BOOL flag that indicates whether or not the manager or operation is allowed to continue processing in the background. The value of this property is set by a delegate call during configuration of the manager or operation. This can give the flexibility of allowing only certain types of operations to process in the background state.

The second property is the assigned backgroundTaskID for the operation. Regardless of the value of the first flag, we still always set the backgroundTaskID to ensure that the operation is not immediately killed when the app enters the background state. We want to be able to have enough time to review it and either let it continue or cancel it.

When the appDelegate signals that the app is moving to the background state, our singleton that manages the TICDS system makes a call to the DocumentSyncManager to cancelNonBackgroundStateOperations. This causes the DSM to go through each operation in its three queues and check the shouldContinueProcessingInBackgroundState flag. If it is NO, then the op receives a cancel request. If it is YES, it is allowed to continue processing. We also call the same method on the App Sync Manager which reviews the ops in it's two operation queues.