Search code examples
iosnsoperationnsoperationqueuensmutableurlrequest

NSOperationQueue cancels the current NSOperation when network switched


I am uploading a video to server using POST method. Uploading a video is placed inside the main() of NSOperation . After that it was queued up into NSOperationQueue.

Current operation gets failed when network was switched between wi-fi and cellular data.

How handle the network switching NSOperation failing issue.

Am using sendSynchronousRequest: for video upload

I tried using AFNetworking but results remains the same


Solution

  • Few suggestions here.

    First of all you need to set up a mechanism for knowing when you are swicthing from WiFi to cellular. If so, you need to send the cancel message to the operation in order to cancel it.

    Then, you need to transform your operations into an asynchronous operation (override asynchronous property, the old one was named concurrent). Each time you upload a chunk of data you need to verify if the operation has been cancelled, checking isCancelled property, and rolback if necessary.

    Using a synchronous operations prevents you to cancel the task you are running.

    A similar approach can be used with NSUrlSession (see invalidateAndCancel method). In this case, you could avoid to use operations to wrap an upload task on it.

    Let me know if you need something else.