Swift-URLSession(2) 后台下载

2019-12-26  本文已影响0人  见哥哥长高了

利用URLSession实现后台下载用法比较简单:

    func backgroundDownloadTest(){
        
        //url实例
        let url: URL = URL.init(string: "http://pic1.win4000.com/pic/5/9e/4933293953.jpg")!
        
        //会话配置
        let config = URLSessionConfiguration.background(withIdentifier: "backgroundID")
        
        //会话对象
        let session = URLSession(configuration: config, delegate: self, delegateQueue: .main)
        
        //启动会话
        session.downloadTask(with: url).resume()
        
    }

以上是初始化并启动会话的步骤。接下来需要在会话代理类中实现URLSessionDownloadDelegate中的方法:

urlSession(_:downloadTask:didFinishDownloadingTo:)

下载完成之后就回调
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        /*
         下载完成 开始沙盒迁移
         */
        print("下载完成--\(location.path)")
        let locationPath = location.path
        
        //拷贝到用户目录 文件名以时间戳命名
        let documents = NSHomeDirectory()+"/Documents/" + self.getTimestampStr() + ".jpg"
        
        print("迁移地址--\(documents)")
        
        let fileManager = FileManager.default
        
        try! fileManager.moveItem(atPath: locationPath, toPath: documents)
 
    }

    func getTimestampStr() -> String {
        
        let date = NSDate()
        
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
        print("当前时间-\(dateformatter.string(from: date as Date))")
        
        let timeInteval: TimeInterval = date.timeIntervalSince1970
        let timeStamp = Int(timeInteval)
        
        print("当前时间时间戳-\(timeStamp)")

        return String(timeStamp)
    }

urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)

    //下载进度监控
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        
        print("bytesWritten \(bytesWritten), totalBytesWritten \(totalBytesWritten), totalBytesExpectedToWrite \(totalBytesExpectedToWrite)")
        
        print("下载进度:\(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))\n")

    }

只是完成以上工作,还不能完成后台下载任务,还需要以下步骤:
AppDelegate中

    //用于保存后台下载的completionHandler
    var backgroundSessionCompletionHandler: (() -> Void)?
    
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        self.backgroundSessionCompletionHandler = completionHandler
    }

最后会话代理实现:urlSessionDidFinishEvents(forBackgroundURLSession:)

    // 告诉委托排队等待会话的所有消息都已传递。 (Tells the delegate that all messages enqueued for a session have been delivered.)
    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("后台任务下载回来")
        DispatchQueue.main.async {
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
            backgroundHandle()
        }
    }

到此,后台下载就可以顺利完成了。

上一篇下一篇

猜你喜欢

热点阅读