Upload file error handling using URLSessionConfiguration.background and uploadTask

I am using URLSessionConfiguration.background and uploadTask to upload a file from an iOS app.

    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?

URLSession distinguishes between:

  • Transport errors, which are problems getting the request to the server or getting the response back from the server

  • Server errors, which originate on the server, like the 4xx or 5xx you mentioned

When a request completes the session calls your urlSession(_:task:didCompleteWithError:) delegate method. If there’s a transport error, it’s in the error parameter. If that’s nil, look in the response for a server error. Specifically, grab task.response, cast it to an HTTPURLResponse, and look at its stateCode field:

let response = task.response
let httpResponse = (response as! HTTPURLResponse)
let status = httpResponse.statusCode

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Upload file error handling using URLSessionConfiguration.background and uploadTask
 
 
Q