Cra*_*igH 5 ios swift alamofire
我有一系列我想下载的视频文件.我正在使用for循环来下载它们.然而,当循环运行时,所有文件并行下载,导致应用程序挂起,UI冻结,CPU使用通过屋顶.
for url in urlArray{
downloadfile(url)
}
Run Code Online (Sandbox Code Playgroud)
我有一个函数,下载给定URL的文件.
func downloadFile(s3Url:String)->Void{
Alamofire.download(.GET, s3Url, destination: destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
println(totalBytesRead)
}
.response { request, response, _, error in
println(response)
}
}
Run Code Online (Sandbox Code Playgroud)
如何更改此设置,以便文件不会同时下载?另外,如何检查下载是否已完成,以便我可以更新我的UI?
LK *_*ung 12
func downloadFile(var urlArray:[String])->Void{
if let s3Url = urlArray.popLast(){
Alamofire.download(.GET, s3Url, destination: destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
println(totalBytesRead)
}
.response { request, response, _, error in
downloadFile(urlArray)
println(response)
}
}
}
Run Code Online (Sandbox Code Playgroud)
swift 3.0:
func downloadFile(urlArray:[String])->Void{
var urlArray = urlArray
if let s3Url = urlArray.popLast(){
Alamofire.download(.GET, s3Url, destination: destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
println(totalBytesRead)
}
.response { request, response, _, error in
downloadFile(urlArray)
println(response)
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以做的是在文件下载完成后调出另一个函数(即totalBytesRead> = totalBytesExpectedToRead)。在该功能中,从列表中弹出下一项,然后使用新的URL再次调用下载功能。您可以创建一个包含所有URL的数组,并且在需要新项目时,将其从数组中删除,然后将其传递给下载功能。检查数组是否为空,如果为空,则说明已下载完所有内容。
您不能只使用循环的原因是Alamofire请求始终是异步的,因此在发出请求后,控件将立即返回,并且程序将在下载任何数据之前继续执行。
| 归档时间: |
|
| 查看次数: |
5620 次 |
| 最近记录: |