func startDownload(audioUrl:String) -> Void {
let fileUrl = self.getSaveFileUrl(fileName: audioUrl)
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
return (fileUrl, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(audioUrl, to:destination)
.downloadProgress { (progress) in
self.surahNameKana.text = (String)(progress.fractionCompleted)
}
.responseData { (data) in
// at this stage , the downloaded data are already saved in fileUrl
self.surahNameKana.text = "Completed!"
}
}
let url = "https://httpbin.org/stream/100" // this is for example..
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, url, parameters: params, encoding: ParameterEncoding.URL,destination:destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
// Here you can update your progress object
print("Total bytes read on main queue: \(totalBytesRead)")
print("Progress on main queue: \(Float(totalBytesRead) / Float(totalBytesExpectedToRead))")
}
}
.response { request, _, _, error in
print("\(request?.URL)") // original URL request
if let error = error {
let httpError: NSError = error
let statusCode = httpError.code
} else { //no errors
let filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
print("File downloaded successfully: \(filePath)")
}
}
3条答案
按热度按时间0tdrvxhp1#
在Alamofire中监控进度的方法是在
Request
上使用progress
闭包。更多关于用法的详细信息可以在README中找到。虽然README中的示例演示了下载请求的用法,但它仍然适用于数据请求。需要注意的一点是,对于数据请求,服务器并不总是能提供完美的报告。原因是服务器在流式传输数据之前并不总是报告准确的内容长度。如果内容长度未知,则会调用progress闭包,但
totalExpectedBytesToRead
将始终为-1
。在这种情况下,只有在知道下载数据的大致大小时,才能报告准确的进度。然后,可以将大致数字与
totalBytesRead
值结合使用,以计算估计的下载进度值。bogh5gae2#
Alamofire 4.0和雨燕4.x
xzabzqsa3#
要为Alamofire〉= 3.0的Swift 2.x用户下载进度: