使用urlsessionconfiguration.background和uploadtask上传文件错误处理
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建这样的上传任务:
您可以在回调中处理错误和响应,替代
您可以查看
urlsessionTaskdeletelegate
“ https://developer.apple.com/documentation/foundation/urlsessiondatadelegate” rel =“ nofollow noreferrer”>
urlsessiondatadelegate
用于上传任务的精细控制。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.urlsession.uploadtask不处理HTTP服务器端错误。它仅针对客户端或网络问题处理重试和错误。
必须从将其投入到HTTPURLRESPONSE的任务响应中检索HTTP状态/错误。
直接从uploadTask调用(不受背景urlsession的支持):
或者,如果您使用的是背景urlsession,则来自urlsessiontaskdelegate:
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: