Search code examples
iosdispatch-async

ios cancel dispatch_async task


I have a background task that upload images and videos to the server.

The user can cancel this operation in the middle.

I was wondering if there is an easy way to notify the tasks to stop instead of having a boolean that needs to be checked in order to stop

(and the main problem is that the user can go back to the process once again and re-activate the boolean before the "bad" video finishes uploading)


Solution

  • NSOperationQueue has support for canceling operations. So, for example, you can create a series of NSOperations and add them to an NSOperationQueue and then message -cancelAllOperations to the queue when you don't need it to complete.

    Then when the user goes back the operation will be created again and the request will be sent in the queue.

    Using this is probably the better solution. Killing it is a risky endeavor that can lead to some volatile and unpredictable behaviors. Killing the thread is often a bad idea because of allocation and retains we can't necessarily follow.