作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 URLSession 的帮助下快速上传文件。但问题是我没有获得上传进度。我没有使用任何多部分请求。我只是在请求正文中发送视频数据。
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{
}
请告诉我如何获得上传了多少字节的进度?
最佳答案
您需要实现 urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)
委托(delegate)方法。为此,您需要创建自己的 session 并设置其委托(delegate)。
您还应该使用上传任务。这避免了将文件加载到内存中的需要。
这是 do
block 中的更新代码:
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
}
关于ios - 如何在没有多部分的情况下获取文件上传进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50332397/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!