使用urlsessionconfiguration.background和uploadtask上传文件错误处理

发布于 2025-02-01 07:41:17 字数 714 浏览 3 评论 0原文

我正在使用urlsessionConfiguration.background和uploadTask从iOS应用程序上传文件。

上传会话是按照以下方式配置的:

let configuration = URLSessionConfiguration.background(withIdentifier: "com.mycompany.myapp.fileUploader")
configuration.isDiscretionary = false
configuration.allowsCellularAccess = true
uploadURLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

请求是:

request.httpMethod = "POST"
request.setValue("application/octect-stream", forHTTPHeaderField: "Content-Type")


let task = uploadURLSession.uploadTask(with: request, fromFile: fileURL)

我想了解如何管理错误处理。

urlsession.uploadtask如何处理HTTP错误4xx或5xx?

如何在5xx错误上触发重试?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞琼窗梦回ˉ 2025-02-08 07:41:17

创建这样的上传任务:

let task = uploadSession?.uploadTask(with: request, fromFile: fileURL, completionHandler: { data, response, error in
        if let error = error {
            print("Upload error: \(error.localizedDescription)")
        } else {
            if let response = response as? HTTPURLResponse {
                print("Response status code: \(response.statusCode)")
            }
        }
    })

    task?.resume()

您可以在回调中处理错误和响应,替代
您可以查看 urlsessionTaskdeletelegate“ https://developer.apple.com/documentation/foundation/urlsessiondatadelegate” rel =“ nofollow noreferrer”> urlsessiondatadelegate 用于上传任务的精细控制。

Create the upload task like this:

let task = uploadSession?.uploadTask(with: request, fromFile: fileURL, completionHandler: { data, response, error in
        if let error = error {
            print("Upload error: \(error.localizedDescription)")
        } else {
            if let response = response as? HTTPURLResponse {
                print("Response status code: \(response.statusCode)")
            }
        }
    })

    task?.resume()

you can handle errors and responsecode in the callback ☝️, alternatively
you can look at URLSessionTaskDelegate and and URLSessionDataDelegate for a fine-grained control over the upload task.

若能看破又如何 2025-02-08 07:41:17

urlsession.uploadtask不处理HTTP服务器端错误。它仅针对客户端或网络问题处理重试和错误。

必须从将其投入到HTTPURLRESPONSE的任务响应中检索HTTP状态/错误。

直接从uploadTask调用(不受背景urlsession的支持):

let task = uploadSession?.uploadTask(with: request, fromFile: fileURL, completionHandler: { data, response, error in
    if let error = error {
        print("Upload error:\(error)")
        //Client side error
        return
    }
    
    guard let res = response as? HTTPURLResponse else {
        print("Upload completed with response:\(response.description ?? "undefined")")
        //It should not happen at all
        return
    }
    
    if (200...299).contains(res.statusCode) {
        print("Upload completed successfully. Status code:\(res.statusCode)")
    }
    else if (400...499).contains(res.statusCode) {
        print("Upload fatal issue. Status code:\(res.statusCode)")
        //Fatal issue, do not retry the upload
    }
    else if (500...599).contains(res.statusCode) {
        print("Upload issue. Status code:\(res.statusCode)")
        //Schedules a new uploading task for the file
    }
    else {
        print("Upload completed with status code:\(res.statusCode)")
    }
})

或者,如果您使用的是背景urlsession,则来自urlsessiontaskdelegate:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if let error = error {
        print("Upload error:\(error)")
        //Client side error
        return
    }

    guard let res = task.response as? HTTPURLResponse else {
        print("Upload completed with response:\(task.response?.description ?? "undefined")")
        //It should not happen at all
        return
    }

    if (200...299).contains(res.statusCode) {
        print("Upload completed successfully. Status code:\(res.statusCode)")
    }
    else if (400...499).contains(res.statusCode) {
        print("Upload fatal issue. Status code:\(res.statusCode)")
        //Fatal issue, do not retry the upload
    }
    else if (500...599).contains(res.statusCode) {
        print("Upload issue. Status code:\(res.statusCode)")
        //Schedules a new uploading task for the file
    }
    else {
        print("Upload completed with status code:\(res.statusCode)")
    }
}

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):

let task = uploadSession?.uploadTask(with: request, fromFile: fileURL, completionHandler: { data, response, error in
    if let error = error {
        print("Upload error:\(error)")
        //Client side error
        return
    }
    
    guard let res = response as? HTTPURLResponse else {
        print("Upload completed with response:\(response.description ?? "undefined")")
        //It should not happen at all
        return
    }
    
    if (200...299).contains(res.statusCode) {
        print("Upload completed successfully. Status code:\(res.statusCode)")
    }
    else if (400...499).contains(res.statusCode) {
        print("Upload fatal issue. Status code:\(res.statusCode)")
        //Fatal issue, do not retry the upload
    }
    else if (500...599).contains(res.statusCode) {
        print("Upload issue. Status code:\(res.statusCode)")
        //Schedules a new uploading task for the file
    }
    else {
        print("Upload completed with status code:\(res.statusCode)")
    }
})

or, if you are using a background URLSession, from the URLSessionTaskDelegate:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if let error = error {
        print("Upload error:\(error)")
        //Client side error
        return
    }

    guard let res = task.response as? HTTPURLResponse else {
        print("Upload completed with response:\(task.response?.description ?? "undefined")")
        //It should not happen at all
        return
    }

    if (200...299).contains(res.statusCode) {
        print("Upload completed successfully. Status code:\(res.statusCode)")
    }
    else if (400...499).contains(res.statusCode) {
        print("Upload fatal issue. Status code:\(res.statusCode)")
        //Fatal issue, do not retry the upload
    }
    else if (500...599).contains(res.statusCode) {
        print("Upload issue. Status code:\(res.statusCode)")
        //Schedules a new uploading task for the file
    }
    else {
        print("Upload completed with status code:\(res.statusCode)")
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文