Alamofire - 后臺下載

上一篇有略講URLSession處理后臺下載 Alamofire(一)

這一篇來研究下Alamofire - 后臺下載

configuration - init 源碼

commonInit - 源碼
接下來進入正題
//封裝了一層單例 - 后臺下載管理類(在GitHub上查找的資料某位大神提供)
struct LGBackgroundManger {
    
    static let shared = LGBackgroundManger()
    
    let manager: SessionManager = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "com.lgcooci.AlamofireTest.demo")
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
//        configuration.timeoutIntervalForRequest = 10
//        configuration.timeoutIntervalForResource = 10
//        configuration.sharedContainerIdentifier = "group.com.lgcooci.AlamofireTest"
        
        return SessionManager(configuration: configuration)
    }()
}

        // 鏈式請求 -- 本質調用函數方法的時候不斷的返回對象、這個對象又可以不斷調用下層函數方法 
        LGBackgroundManger.shared.manager
            .download(self.urlDownloadStr1) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
                let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
                let fileUrl     = documentUrl?.appendingPathComponent(response.suggestedFilename!)
                //返回元祖
                return (fileUrl!,[.removePreviousFile,.createIntermediateDirectories])
            }
            .response { (downloadResponse) in
                print("下載回調信息: \(downloadResponse)")
            }
            .downloadProgress { (progress) in
                print("下載進度 : \(progress)")
            }

// 后臺進行載完成 -- 進行刷新主線程【AppDelegate】
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        print("hello - \(identifier)")
       LGBackgroundManger.shared.manager.backgroundCompletionHandler = completionHandler
    }

為什么要做成單例,URLSession的時候不是挺好的?

  • 如果你是SessionManager.defalut 顯然是不可以的!畢竟要求后臺下載,那么我們的會話session的配置
  • URLSessionConfiguration是要求background模式的
    如果你配置出來不做成單例,或者不被持有!在進入后臺就會釋放,網絡也就會報錯:Error Domain=NSURLErrorDomain Code=-999 "cancelled"
  • 應用層與網絡層也可以達到分離。
  • 能夠幫助在AppDelegate 的回調方便直接接收
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。