0

I want to upload a file to a server using NSURLSession.

Cases Are: 1. It should resume uploading a file to the server from where it stopped because of app crash. 2. It should handle background upload as well.

Abhishek
  • 184
  • 12

2 Answers2

0

Try AFNetworking Library to upload image asynchronously.You can find a brief example in this thread.

Community
  • 1
  • 1
Burhan Ahmad
  • 728
  • 5
  • 13
0

You should use background NSURLSession. If your app crashed or user left the app while upload was in progress, with a background NSURLSession the upload would continue seamlessly in the background. When the upload is done, your app will be notified of this via the delegate (and if your app wasn't alive at the time the download finished, it will be started in a background mode, at which point you can do whatever cleanup you need).

So create NSURLSessionConfiguration with backgroundSessionConfigurationWithIdentifier, and then instantiate a NSURLSession with that configuration.

There are a few caveats:

  • You cannot use completion handler pattern. You have to use delegate-based implementation.

  • You have to implement handleEventsForBackgroundURLSession in the app delegate, capturing the completionHandler it passes you and also instantiate the background session again. Likewise, in your NSURLSession delegate methods, you have to implement URLSessionDidFinishEventsForBackgroundURLSession, which will call the saved completion handler.

For more information, see Background Task Considerations in URL Session Programming Guide, see a section of the same name (but different text) in the NSURLSession class reference, or see the WWDC 2013 What's New in Foundation Networking, where Apple first introduced us to background sessions.

Rob
  • 415,655
  • 72
  • 787
  • 1,044