Ios Alamofire:如何按顺序下载文件
我有一系列的视频文件要下载。我使用for循环下载它们中的每一个。然而,当循环运行时,所有文件并行下载,这导致应用程序挂起,UI冻结,CPU使用过度Ios Alamofire:如何按顺序下载文件,ios,swift,alamofire,Ios,Swift,Alamofire,我有一系列的视频文件要下载。我使用for循环下载它们中的每一个。然而,当循环运行时,所有文件并行下载,这导致应用程序挂起,UI冻结,CPU使用过度 for url in urlArray{ downloadfile(url) } 我有一个函数,可以下载给定URL的文件 func downloadFile(s3Url:String)->Void{ Alamofire.download(.GET, s3Url, destination: destination)
for url in urlArray{
downloadfile(url)
}
我有一个函数,可以下载给定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)
}
}
我如何才能更改此设置,使文件不会同时下载?此外,如何检查下载是否完成,以便更新UI?当文件下载完成时,您可以调用另一个函数(即totalBytesRead>=totalBytesExpectedToRead)。在该函数中,从列表中弹出下一项,并使用新URL再次调用下载函数。您可以创建一个包含所有URL的数组,当您需要一个新项目时,将其从数组中删除并传递给下载函数。检查数组是否为空,如果为空,则表示您已完成下载所有内容 不能像现在这样使用循环的原因是,Alamofire请求始终是异步的,因此在发出请求后,控制立即返回,并且在下载任何数据之前,程序继续运行
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)
}
}
}
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)
}
}
}
我希望这会有所帮助
var urlArray:[String] =["your file link","your file link"]
func downloadFile(url: String)->Void{
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(
url,
method: .get,
encoding: JSONEncoding.default,
to: destination).downloadProgress(closure: { (progress) in
//progress closure
}).response(completionHandler: { (DefaultDownloadResponse) in
//here you able to access the DefaultDownloadResponse
//result closure
self.urlArray.removeFirst()
if DefaultDownloadResponse.response?.statusCode == 200 {
print(DefaultDownloadResponse.destinationURL)
if !self.urlArray.isEmpty{
self.downloadFile(url: self.urlArray[0])
}
}
})
}
@马特,你能举个例子吗?我尝试在NSBlockOperation中包装下载文件,但没有成功。ie:let operation=NSBlockOperation{()->Void在println(“开始下载”)self.downloadfile(url!)}队列中。addOperation(operation)应该是它的全部内容。什么不起作用?@mattt-it仍然同时下载它们。我现在放弃了一个调用自身的函数,这让我有点害怕,但它的工作原理和预期的一样。(这样做,世界不应该爆炸…)不幸的是,
var
将在swift3中被删除。我们如何更改这些代码?您在哪里听说var被删除了?同时将一个控制器切换到另一个控制器是否有效,我是说在后台?