第47月第11天 iOS 文件下载Download,支持断点续传、后台下载、设置下载并发数

1. iOS 文件下载Download,支持断点续传、后台下载、设置下载并发数

 /// 开始下载
    private func start(url: String) {
        guard url.dw_isURL else { return }
        if let task = getTask(url: url) {
            
            let runningModels = sessionModels.filter { (key, value) -> Bool in
                return value.states == .start
            }
            
            if let model = getSessionModel(taskIdentifier: task.taskIdentifier) {
                if runningModels.count < maxDownloadCount {
                    task.resume()
                    model.states = .start
                } else {
                    model.states = .waiting
                }
            }
        }
    }


private func waitingTask() {
        let waitingModel = sessionModels.filter { (key, value) -> Bool in
            return value.states == .waiting
        }
        if let sessionModel = waitingModel.first {
            let model = sessionModel.value
            if let url = model.model.url {
                start(url: url)
            }
        }
    }

 

extension DownloadManager: URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        
        if let error = error, error.localizedDescription == "cancelled" { return }
        
        guard let model = sessionModels["\(task.taskIdentifier)"],
            let url = model.model.url,
            url.dw_isURL else { return }
        
        if let error = error {
            if model.states != .suspended && error.localizedDescription != "The request timed out." {
                debugPrint("下载失败")
                model.states = .failed
            }
        } else {
            debugPrint("下载完成")
            model.states = .completed
        }
        
        // 关闭流
        model.stream?.close()
        model.stream = nil
        // 清除任务
        tasks.removeValue(forKey: url.dw_getFileName)
        sessionModels.removeValue(forKey: "\(task.taskIdentifier)")
        
        waitingTask()
    }
}

 

 

 

https://www.jianshu.com/p/6c8ac936e57a

posted @ 2020-08-12 08:36  lianhuaren  阅读(275)  评论(0编辑  收藏  举报