image.png
import UIKit
/// 遵守协议
class ViewController: UIViewController,URLSessionDownloadDelegate {
@IBOutlet weak var progressView: UIProgressView! // 进度条
var downloading = false // 记录是否在下载
var downloadData: Data? // 记录已下载的数据
lazy var session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.isDiscretionary = true //自由决定选择哪种网络状态进行下载数据
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
return session
}()
// MARK: - 下载任务
lazy var downloadTask : URLSessionDownloadTask = {
let request = URLRequest.init(url: URL(string: "https://hjmys.oss-cn-shenzhen.aliyuncs.com/911f7716b1b4a4edd583dd604db47ae468cf4b65.mp4")!)
let downloadTask = session.downloadTask(with: request)
return downloadTask
}()
override func viewDidLoad() {
super.viewDidLoad()
}
///按钮点击事件
@IBAction func buttonClick(_ btn: UIButton) {
switch btn.tag {
case 100:
print("开始")
startDownload()
case 101:
print("暂停")
pauseDownload()
case 102:
print("恢复")
resumeDownload()
default:
break
}
}
// MARK: - 开始下载
func startDownload() {
downloading = true
self.downloadTask.resume()
}
// MARK: - 暂停下载
func pauseDownload() {
self.downloadTask.cancel { [weak self] (resumeData) in
self?.downloadData = resumeData
}
downloading = false
}
// MARK: - 恢复下载
func resumeDownload(){
if (downloadData != nil) {
self.downloadTask = self.session.downloadTask(withResumeData: self.downloadData!)
self.downloadTask.resume()
self.downloading = true
}
}
// 下载代理方法,下载结束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("下载结束")
}
// 下载代理方法,监听下载进度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let request = URLRequest.init(url: URL(string: "https://hjmys.oss-cn-shenzhen.aliyuncs.com/911f7716b1b4a4edd583dd604db47ae468cf4b65.mp4")!)
if downloadTask.currentRequest?.url == request.url {
print("是当前任务")
} else {
print("不是当前任务")
}
if downloading == true {
DispatchQueue.main.async {
print(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
self.progressView.setProgress(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite), animated: true)
}
}
}
// 下载代理方法,下载偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
print("下载偏移")
// 下载偏移,主要用于暂停续传
}
/*
* 该方法下载成功和失败都会回调,只是失败的是error是有值的,
* 在下载失败时,error的userinfo属性可以通过NSURLSessionDownloadTaskResumeData
* 这个key来取到resumeData(和上面的resumeData是一样的),再通过resumeData恢复下载
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
}
Dome
网友评论