9

I am developing an app to upload multiple files using NSURLSession, right now my files are successfully uploaded. But now what i want to achieve is to pause,resume and cancel the uploads just like we do in download tasks. Is it possible.? Any help would be appreciated. Thnx

Andrey Chernukha
  • 20,316
  • 16
  • 89
  • 153
Tabish Sohail
  • 922
  • 1
  • 8
  • 19
  • you cannot pause and then resume an upload task when using nsurlsession – Andrey Chernukha Jan 07 '15 at 06:48
  • Ok.But what in that case when device goes offline while uploading and when it comes back onilne ? @Andrey – Tabish Sohail Jan 07 '15 at 06:54
  • start it over from the very beginning – Andrey Chernukha Jan 07 '15 at 06:58
  • Is there any alternate way to do that in URLSession..Because i have to achieve this as this is the requirement for my project. Please help – Tabish Sohail Jan 07 '15 at 08:31
  • Do you upload your files to some kind of service or your own server? There may be some variants depending on your answer, not many though. Anyway I think you must give up using NSURLSession for uploads – Andrey Chernukha Jan 07 '15 at 09:40
  • Can you explain why you feel that it's not possible to suspend/resume upload tasks? Upload tasks respond to the suspend/resume methods on the base class. Just wondering if there's some edge case that exists that you're aware of that's not apparent in the docs. @AndreyChernukha – Alfie Hanssen Dec 07 '15 at 21:45

2 Answers2

7

I have studied alot but could find nothing .After i tried this on my code assuming this as a download task ,I came to know that we can "pause , resume" upload tasks as well using NSURLSession just we do in downloading tasks.

To pause a task simply call [yourUploadTask suspend]; to resume [yourUploadTask resume]; To cancel [yourUploadTask cancel];

It might help someone working on uploadTask using NSURLSession.

Tabish Sohail
  • 922
  • 1
  • 8
  • 19
0

You can try to use the suspend(), resume() methods inherited from URLSessionTask, but resume() will cause the upload to fail. You can work around this in your upload class by automatically retrying upload errors (i.e. any non-permanent error other than 400s), but that means restarting every pending upload again from the beginning and losing the data that's already been uploaded.

There isn't a cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) for URLSessionUploadTask like there is for URLSessionDownloadTask, so there is no state data saved to restore and continue the upload. To implement one would require rolling our own, which I haven't done (yet), but I believe requires specific server support to implement, and the user of lower level networking APIs.

SafeFastExpressive
  • 3,003
  • 2
  • 26
  • 34