2

I've been to reading about NSURLSession and how to upload data in the background, but just can't figure it out. So I was hoping someone could help me.

I have an app that searches for a user's location and sends data to a server, and that part is working fine. If the app is terminated (for whatever reason), the app gets woken up again when it receives a location update. When the app is woken up, it has about 10 seconds to process any information before getting terminated again. With a very slow Internet connection it can sometimes take more than 10 seconds to contact the server and get a response. That's why I was hoping to use some background mode in iOS to contact the server and get a response.

Now, I was looking into NSURLSession, but can't seem to get it working. I basically just need to send a JSON to the server and then get the server's response back.

I have been following a tutorial, but I keep getting this exception:

NSURLSessionUpload[4512:66325] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks from NSData are not supported in background sessions.'

Here's the tutorial in case you want to check it out.

https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-3-upload-3a5be9a69950

Could some post some sample code that I could look into?

Lachezar
  • 6,523
  • 3
  • 33
  • 34
Pætur Magnussen
  • 901
  • 1
  • 11
  • 24
  • 1
    You have to save the body of the request in a file and then use the rendition of upload task that takes file path rather than `NSData`. – Rob Jul 24 '15 at 14:22
  • See [Handling iOS Background Sessions](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW26) for additional considerations (e.g., don't use block-based `NSURLSession` methods, implement app delegate handler, etc.). – Rob Jul 24 '15 at 15:00
  • Thanks a lot! Could you post an example? – Pætur Magnussen Jul 24 '15 at 17:43
  • Search for "`NSURLSession` background upload" and you'll find many hits, I think. For example: http://stackoverflow.com/a/23738200/1271826 – Rob Jul 24 '15 at 18:29

0 Answers0