美文网首页
Swift-DownloadTask 断点下载文件

Swift-DownloadTask 断点下载文件

作者: 紫云夕月 | 来源:发表于2021-09-15 13:37 被阅读0次
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()

相关文章

  • Swift-DownloadTask 断点下载文件

  • Android下载文件(一)下载进度&断点续传

    索引 Android下载文件(一)下载进度&断点续传 Android下载文件(二)多线程并发&断点续传(待续) A...

  • 基于Okhttp实现断点下载(续传)和分片下载

    断点下载/续传 断点下载是针对下载大文件需求的一种优化机制,可以从上次下载的断点处继续下载。断点续传原理也相同,只...

  • NSURLSession

    NSURLSession 发送一般的GET和POST请求 下载文件不需要离线断点(小文件) 下载文件需要离线断点(...

  • Android 零碎知识点和技巧

    使用DownloadManager下载文件 下载文件 监听下载结果 文件下载断点续传 1.获取已下载的文件长度. ...

  • NSURLSession实现断点下载

    断点续传概述 断点续传就是从文件上次中断的地方开始重新下载或上传数据,而不是从文件开头。(本文的断点续传仅涉及下载...

  • IOS 断点续传原理浅析(第一篇)

    断点续传概述: 断点续传就是从文件上次中断的地方开始重新下载或上传数据,当下载大文件的时候,如果没有实现断点续传功...

  • iOS-16 断点续传 下载

    断点续传概述: 断点续传就是从文件上次中断的地方开始重新下载或上传数据,当下载大文件的时候,如果没有实现断点续传功...

  • AFNetworking

    上传 单图片上传 多文件上传 下载 AFNetworking 断点下载

  • NSURLSession

    使用步骤: Task: 下载文件: 代理的方式: 大文件下载: 文件暂停和恢复: 断点下载原理: 如果下载中途失败...

网友评论

      本文标题:Swift-DownloadTask 断点下载文件

      本文链接:https://www.haomeiwen.com/subject/urpuvltx.html