ALDownloadManager包含了断点续传,多文件顺序下载,多文件同时下载
同时下载
顺序下载
外层调用:
单文件下载
ALDownloadManager.shared.download(url: self.testUrl)?.downloadProgress(nil).downloadResponse(nil)
多文件同时下载
ALDownloadManager.shared.changeDownloadState()
多文件顺序下载
ALDownloadManager.shared.changeWaitState(completeClose: nil)
具体实现:
下载方法(默认断点续传)
func download() {
if let resumeData = cancelledData {
let destination = createDestination(destinationPath: destinationPath)
downloadRequest = manager?.download(resumingWith: resumeData, to: destination).response(completionHandler: { [weak self] (defresponse) in
self?.cancelledData = defresponse.resumeData
}).downloadProgress(closure: { (progress) in
self.progress = progress
}).response(completionHandler: { (defaultResponse) in
self.respons = defaultResponse
})
}else{
let destination = createDestination(destinationPath: destinationPath)
if let url = downloadurl {
downloadRequest = manager?.download(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil, to: destination).response(completionHandler: { [weak self] (defresponse) in
self?.cancelledData = defresponse.resumeData
}).downloadProgress(closure: { (progress) in
self.progress = progress
}).response(completionHandler: { (defaultResponse) in
self.respons = defaultResponse
})
}
}
self.state = ALDownloadState.Download
}
cancelledData 下载失败时的数据,恢复下载时需要用到
downloadRequest 每次下载时重新赋值,保证downloadRequest为最新值
取消下载
func cancel() {
downloadRequest?.cancel()
self.state = ALDownloadState.Cancel
}
Alamofire的取消下载,加上下载状态的改变
挂起
func hangup() {
downloadRequest?.cancel()
self.state = ALDownloadState.Wait
}
下载任务挂起(等待下载): 顺序下载时用到
同时下载
func changeDownloadState() {
self.downloadInfoArray = self.downloadInfoArray?.map({ (info) -> ALDownloadInfo in
if info.state == ALDownloadState.Download || info.state == ALDownloadState.Completed{}
else{
info.download()
}
return info
})
}
正在下载和已经下载完成的任务保持,其余任务改变为下载状态
这里重点说下顺序下载
func changeWaitState(completeClose: ALDownloadCompleteClose?) {
self.completeClose = completeClose
var isDownloadFirst = false
self.downloadInfoArray = self.downloadInfoArray?.map({ (info) -> ALDownloadInfo in
if isDownloadFirst == false {
if info.state == ALDownloadState.Download {
isDownloadFirst = true
return info
}
}
if info.state == ALDownloadState.Completed {}
else{
info.hangup()
}
return info
})
if isDownloadFirst == false {
resumeFirstWillResume()
}
}
如果有任务下载,下载中的第一个任务保持下载状态,其余改变为等待下载;如果没有任务下载,将所有任务改变为等待下载,再下载第一个等待任务,这是我的思路,有更好方法的麻烦告知我