import UIKit
import Foundation
class PublicFunction: NSObject {
//MARK:document文档目录
static func documentPath() -> String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
return documentPath
}
//MARK:文件路径
static func downloadDirectory(path:String) -> String {
let downloadFile = PublicFunction.documentPath() + "/\(path)/"
let fileManager = FileManager.default
if fileManager.fileExists(atPath: downloadFile) == false {
do {
try fileManager.createDirectory(atPath: downloadFile, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
return downloadFile
}
}
import UIKit
class DownloadTaskTool: NSObject, URLSessionDownloadDelegate {
//文件资源地址
var downUrl:String = ""
//保存路径
var savePath:String = ""
//下载进度回调
var progressBlock: ((Float) -> ())?
var currentSession:URLSession?
var downloadTask:URLSessionDownloadTask?
var downloadData:Data = Data()//下载的数据
override init() {
super.init()
let config = URLSessionConfiguration.default
currentSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
}
//MARK:启动断点续传下载请求
func start() {
if downloadData.count > 0 {
self.downloadTask = currentSession?.downloadTask(withResumeData: downloadData)
self.downloadTask?.resume()
} else {
if let Url = URL(string: self.downUrl) {
let request = URLRequest(url: Url)
self.downloadTask = currentSession?.downloadTask(with: request)
self.downloadTask?.resume()
}
}
}
//MARK:取消断点续传下载请求
func cancel() {
self.downloadTask?.cancel(byProducingResumeData: { resumeData in
print(resumeData?.count)
if resumeData != nil {
self.downloadData = resumeData!
}
})
}
//下载代理方法,下载结束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
//保存文件
if !savePath.isEmpty {
//location位置转换
let locationPath = location.path
//移除旧文件
if FileManager.default.fileExists(atPath: savePath) {
do {
try FileManager.default.removeItem(atPath: savePath)
} catch {
print(error)
}
}
//生成新文件
if !FileManager.default.fileExists(atPath: savePath) {
do {
try FileManager.default.moveItem(atPath: locationPath, toPath: savePath)
} catch {
print(error)
}
}
}
}
//下载代理方法,监听下载进度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
//获取进度
let written = (Float)(totalBytesWritten)
let total = (Float)(totalBytesExpectedToWrite)
let pro = written/total
if let onProgress = progressBlock {
onProgress(pro)
}
}
//下载代理方法,下载偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
//下载偏移,主要用于暂停续传
}
}
//退出,会重新开始进度
let downLoadManager = DownloadTaskTool()
self.downLoadManager.downUrl = "https://webfs.ali.kugou.com/202108021358/f8e446476833e4c950f58d07762c4827/KGTX/CLTX001/84ea1667187279849794a9cc96fa0d27.mp3"
let savePath = PublicFunction.downloadDirectory(path: "download") + "111.mp3"
downLoadManager.savePath = savePath
//更新下载进度
downLoadManager.progressBlock = { (progress) in
OperationQueue.main.addOperation {
print("下载进度:\(progress)")
}
}
//开始下载
downLoadManager.start()
//暂停下载
downLoadManager.cancel()