其他分享
首页 > 其他分享> > Alamofire初探(后台下载)

Alamofire初探(后台下载)

作者:互联网

Alamofire后台下载

后台下载

从iOS7以来,苹果推出了NSURLSession后,可以实现后台下载任务

先来看看苹果原生后台下载

let urlString:String = "http://dldir1.qq.com/qqfile/QQforMac/QQ_V6.5.5.dmg"
let config = URLSessionConfiguration.background(withIdentifier: createID())
let session = URLSession.init(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let downloadTask: URLSessionDownloadTask = session.downloadTask(with: URL(string: urlString)!)
downloadTask .resume()
//用于保存后台下载的completionHandler
    var backgroundSessionCompletionHandler: (() -> Void)?
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        
        print("handleEventsForBackgroundURLSession - \(identifier)")
        self.backgroundSessionCompletionHandler = completionHandler
    }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("下载完成 - \(location)")
        let locationPath = location.path
        //拷贝到用户目录(文件名以时间戳命名)
        let documnets = NSHomeDirectory() + "/Documents/" + lgCurrentDataTurnString() + ".dmg"
        //创建文件管理器
        let fileManager = FileManager.default
        
        try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print(" bytesWritten \(bytesWritten)\n totalBytesWritten \(totalBytesWritten)\n totalBytesExpectedToWrite \(totalBytesExpectedToWrite)")
        print("下载进度: \(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))\n")
    }
    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("后台任务下载回来,当前线程-\(Thread.current)")

        DispatchQueue.main.async {
        
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                return
            }
            guard let backHandler = appDelegate.backgroundSessionCompletionHandler else {
                return
            }
            backHandler()
        }
    }

Alamofire后台下载

struct LGBackgroundManger {
    static let shared = LGBackgroundManger()
    let manager: SessionManager = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "com.lgcooci.AlamofireTest.demo")
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        return SessionManager(configuration: configuration)
    }()
}
LGBackgroundManger.shared.manager
            .download(urlString, method: .get, parameters: nil) {
                (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
                let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
                let fileUrl = documentUrl?.appendingPathComponent(response.suggestedFilename ?? "123.dmg")
                return (fileUrl!, [.createIntermediateDirectories,.removePreviousFile])
            }.response { (downloadResponse) in
                print("下载回调信息:\(downloadResponse)")
            }.downloadProgress { (progress) in
                print("下载进度:\(progress)")
        }
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        
        print("handleEventsForBackgroundURLSession - \(identifier)")
        LGBackgroundManger.shared.manager.backgroundCompletionHandler = completionHandler
    }

标签:completionHandler,print,session,let,初探,后台,Alamofire,下载
来源: https://blog.csdn.net/GuanZeJun123/article/details/101296696