如何在没有multipart的情况下获取文件上传的进度?

时间:2018-05-14 14:08:24

标签: ios swift nsurlsession

我在URLSession的帮助下在swift中上传文件。但问题是我上传时没有进展。我没有使用任何多部分请求。我只是在请求正文中发送视频数据。

let urlStr = UserDefaults.standard.value(forKey: "Resumable") as? String ?? ""
let url = URL(string: urlStr)

do{
    var request = try URLRequest(url: url!, method: .put)
    // request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    // request.setValue("300000", forHTTPHeaderField: "X-Upload-Content-Length")
    request.setValue("video/*", forHTTPHeaderField: "Content-Type")
    request.setValue("278", forHTTPHeaderField: "Content-Length")
    request.timeoutInterval = 60.0

    let path = Bundle.main.path(forResource: "video", ofType: "mov")
    let videodata: NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData

    request.httpBody = videodata as Data

    let session = URLSession.shared
    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
        if let httpResponse = response as? HTTPURLResponse {
            print(httpResponse.allHeaderFields)

            if httpResponse.statusCode != 200 {
                return
            }else{
                if let url = httpResponse.allHeaderFields["Location"] as? String{
                }
            }
        }
    })
    task.resume()
}catch{
}

请告诉我如何获得上传了多少字节的进度?

1 个答案:

答案 0 :(得分:2)

您需要实现urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)委托方法。要做到这一点,您需要创建自己的会话并设置其委托。

您还应该使用上传任务。这样就无需将文件加载到内存中。

此处有do块内的更新代码:

var request = try URLRequest(url: url!)
// request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// request.setValue("300000", forHTTPHeaderField: "X-Upload-Content-Length")
request.setValue("video/*", forHTTPHeaderField: "Content-Type")
request.setValue("278", forHTTPHeaderField: "Content-Length")
request.timeoutInterval = 60.0

let videoURL = Bundle.main.url(forResource: "video", withExtension: "mov")!

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.uploadTask(with: request, fromFile: videoURL) { (data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        print(httpResponse.allHeaderFields)

        if httpResponse.statusCode != 200 {
            return
        }else{
            if let url = httpResponse.allHeaderFields["Location"] as? String{
            }
        }
    }
}
task.resume()

然后添加:

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
    // update progress as needed
}