Skip to content

Instantly share code, notes, and snippets.

@toddhopkinson
Last active September 27, 2023 01:47
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save toddhopkinson/60cae9e48e845ce02bcf526f388cfa63 to your computer and use it in GitHub Desktop.
Save toddhopkinson/60cae9e48e845ce02bcf526f388cfa63 to your computer and use it in GitHub Desktop.
Upload Very Large Files In Background on iOS - Alamofire.upload multipart in background
// You have a very very large video file you need to upload to a server while your app is backgrounded.
// Solve by using URLSession background functionality. I will here use Alamofire to enable multipart upload.
class Networking {
static let sharedInstance = Networking()
public var sessionManager: Alamofire.SessionManager // most of your web service clients will call through sessionManager
public var backgroundSessionManager: Alamofire.SessionManager // your web services you intend to keep running when the system backgrounds your app will use this
private init() {
self.sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
self.backgroundSessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: "com.lava.app.backgroundtransfer"))
}
}
class VideoUploadClient {
class func upload(videoURL: URL, success: (() -> Void)?, failure: ((Error) -> Void)?) {
Networking.sharedInstance.backgroundSessionManager.upload(multipartFormData: { (multipartData) in
// multipart setup
}, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .post, headers: ["Content-Type":"multipart/form-data"], encodingCompletion: { encodingResult in
// transmission closure
switch (encodingResult) {
// encodingResult success
case .success(let request, let streamingFromDisk, let streamFileURL):
// upload progress closure
request.uploadProgress(closure: { (progress) in
print("upload progress: \(progress.fractionCompleted)")
// here you can send out to a delegate or via notifications the upload progress to interested parties
})
// response handler
request.responseJSON(completionHandler: { response in
switch response.result {
case .success(let jsonData):
// do any parsing on your request's response if needed
success?()
case .failure(let error):
failure?(error)
}
})
// encodingResult failure
case .failure(let error):
failure?(error)
} // end encodingresult switch
}) // end upload call
}
} // end VideoUploadClient class
// meanwhile, from a call site somewhere
// ...
class UploadViewController {
// ...
// assume defined and ready
let localVideoURL = URL(someLocalFile)! // force unwrap just for brevity of example, don't do this in real life.
let successClosure: (() -> Void)? = {
print("succeeded :)")
}
let failClosure: ((Error) -> Void)? = {
print("failed :(")
}
func uploadButtonAction() {
VideoUploadClient.upload(localVideoURL, successClosure, failClosure)
}
}
@prdpsingh402
Copy link

Hello, i am using same Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: "com.lava.app.backgroundtransfer")) for background data transfer but getting this error Error Domain=NSURLErrorDomain Code=-999 "cancelled"

Otherwise, I always get "time out error" while I upload a large file on the server including Images and videos

Please help me out from this.

@jyviko
Copy link

jyviko commented Jun 16, 2020

Hi, tried using this gist but I get an execution error at:
precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.")
I am using Alamofire 5.2.1. Which version of Alamofire are you using to get background URLSessionConfigurations?

@fukemy
Copy link

fukemy commented Jun 27, 2020

not working with alamofire 4 + swift 5

@burkaslarry
Copy link

Authors of Alamofire say the background process is not supported. Any clues or substitutes?

@digvijay1331
Copy link

Hi, tried using this gist but I get an execution error at: precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") I am using Alamofire 5.2.1. Which version of Alamofire are you using to get background URLSessionConfigurations?

same here issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment