Is there really no way to run an UPLOAD task while an iOS app is in the background? This is ridiculous. Been looking at various stuff like NSURLSessionUploadTask
You can continue uploads in the background with iOS 7+ if you use background(withIdentifier:) for the configuration when you instantiate your URLSession
.
Note:
you have to use the delegate-based URLSession
;
you cannot use the completion handler renditions of the task factory methods with background sessions; and
you also have to use uploadTask(with:fromFile:) method, not the Data
rendition.
your app delegate must implement application(_:handleEventsForBackgroundURLSession:completionHandler:) and capture that completion handler which you can then call in your URLSessionDelegate
method urlSessionDidFinishEvents(forBackgroundURLSession:).
By the way, if you don't want to use background NSURLSession
, but you want to continue running a finite-length task for more than a few seconds after the app leaves background, you can request more time with UIApplication
method beginBackgroundTask
. That will give you a little time (formerly 3 minutes, only 30 seconds in iOS 13 and later) complete any tasks you are working on even if the user leave the app.
See Extending Your App's Background Execution Time. Their code snippet is a bit out of date, but a contemporary rendition might look like:
var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid
func initiateBackgroundRequest(with data: Data) {
// Request the task assertion and save the ID.
backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Network Tasks") {
// End the task if time expires.
if self.backgroundTaskID != .invalid {
UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
self.backgroundTaskID = .invalid
}
}
// Send the data asynchronously.
performNetworkRequest(with: data) { result in
// End the task assertion.
if self.backgroundTaskID != .invalid {
UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
self.backgroundTaskID = .invalid
}
}
}
Please don’t get lost in the details here. Focus on the basic pattern: