带进度条的简单 URLSession uploadTask

Chr*_*ris 5 networking ios swift

我完全与 URLSession 和 uploadTask 斗争。实际上,我只想将 json 上传到 Web 服务器,并且在上传过程中应该显示一个简单的进度条。我实现了苹果给出的方法:https : //developer.apple.com/documentation/foundation/url_loading_system/uploading_data_to_a_website

上传工作正常,我得到了回应..到目前为止一切都很好,但我不知道如何在上传过程中显示进度条。我尝试的是在调用包含上传任务的方法之前显示进度条

startActivityIndicator()

    let jsonPackage = JSONIncident(incident: incident)

    jsonPackage.sendToBackend(completion: {
        message, error in
  //Handle the server response




    })

    self.activityIndicator.stopAnimating()
    UIApplication.shared.endIgnoringInteractionEvents()
Run Code Online (Sandbox Code Playgroud)

我意识到这很愚蠢,因为上传任务在另一个线程中异步工作。

我想我必须使用委托,但我不知道以哪种方式。例如,如果我实现 URLSessionTaskDelegate,我必须实现一堆函数,如 isProxy()、isKind()、isMember 等。

您能否提供一个简单的示例,如何在上传任务工作期间显示进度条?那就太好了!非常感谢克里斯

adr*_*din 9

您需要符合 URLSessionTaskDelegate 协议并调用此委托方法:

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
{
    var uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
}
Run Code Online (Sandbox Code Playgroud)

然后为您的进度条使用 uploadProgress 变量。

像这样创建你的会话:

var session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
Run Code Online (Sandbox Code Playgroud)