Uploading video files while iOS app is in background? Uploading video files while iOS app is in background? ios ios

Uploading video files while iOS app is in background?


Surprisingly I got somewhere with this, despite quite a few guides suggesting it was virtually impossible and even Dropbox admitting it has to do a hacky location-based thing.

The code was utilising the NSURLSession class, and for uploading, you use its uploadTaskWithStreamedRequest() method, passing an HTTP request and getting a NSURLSessionUploadTask instance in return.

What wasn't immediately clear to me, however, was that "resuming" that task led to files being uploaded independently from the rest of the app, i.e. when the app is minimised, this task continues until it either completes or iOS forces it to pause.

In a sense I had already achieved what I asked for without realising, however this task can still be interrupted by iOS after a few seconds. The rest of the app is also paused, so communication is hampered until the app is brought back to the front again.

The trick is these two methods:

uploadTaskID = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})

and

UIApplication().sharedApplication().endBackgroundTask(uploadTaskID)

with these in place, any code after the "begin" function will run regardless of whether the app is minimised, and will do so until the "end" function is called. With a bit of tweaking, I've been able to get files to upload sequentially and post a notification when the process is done.

I haven't seen this solution be hinted at so it might be a bad idea, but it seemingly works.