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()
}
}
複製程式碼
如果有任務下載,下載中的第一個任務保持下載狀態,其餘改變為等待下載;如果沒有任務下載,將所有任務改變為等待下載,再下載第一個等待任務,這是我的思路,有更好方法的麻煩告知我
就想要?? 歡迎戳這裡 哈哈哈
發現bug或好的建議歡迎 issues or Email Yvente@163.com