I am using URLSessionConfiguration.background and uploadTask to upload a file from an iOS app.
The upload session is configured in the following way:
let configuration = URLSessionConfiguration.background(withIdentifier: "com.mycompany.myapp.fileUploader")
configuration.isDiscretionary = false
configuration.allowsCellularAccess = true
uploadURLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
and the request is:
request.httpMethod = "POST"
request.setValue("application/octect-stream", forHTTPHeaderField: "Content-Type")
let task = uploadURLSession.uploadTask(with: request, fromFile: fileURL)
I’d like to understand how to manage the error handling.
How the http errors 4xx or 5xx are handled by the URLSession.uploadTask?
How can I trigger the retrying on 5xx errors?
2
Answers
URLSession.uploadTask does not handle the http server side errors. It handles retrying and errors only for client side or network issues.
The http status/error has to be retrieved from the task response casting it to an HTTPURLResponse.
Directly from the uploadTask call (not supported by background URLSession):
or, if you are using a background URLSession, from the URLSessionTaskDelegate:
Create the upload task like this:
you can handle errors and responsecode in the callback ☝️, alternatively
you can look at
URLSessionTaskDelegate
and andURLSessionDataDelegate
for a fine-grained control over the upload task.