Alamofire network

Alamofire鏈接

Alamofire是一個(gè)純粹的網(wǎng)絡(luò)庫,關(guān)于UI的部分有另外的封裝,比如AlamofireImage
AlamofireNetworkActivityIndicator

一、URLSession

步驟

  1. 創(chuàng)建session會話
  2. 根據(jù)url創(chuàng)建dataTask
  3. 取消掛起狀態(tài),resume()
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error == nil {
                print("請求成功 \(String(describing: response))")
            }
        }.resume()

URLSession的三種configuration

        let configuration1 = URLSessionConfiguration.default
        print("configuration1沙盒大小:\(String(describing: configuration1.urlCache?.diskCapacity))")
        print("configuration1內(nèi)存大小:\(String(describing: configuration1.urlCache?.memoryCapacity))")
        
        let configuration2 = URLSessionConfiguration.ephemeral
        print("configuration2沙盒大小:\(String(describing: configuration2.urlCache?.diskCapacity))")
        print("configuration2內(nèi)存大小:\(String(describing: configuration2.urlCache?.memoryCapacity))")

/*
打印結(jié)果:
configuration1沙盒大小:Optional(10000000)
configuration1內(nèi)存大小:Optional(512000)
configuration2沙盒大小:Optional(0)
configuration2內(nèi)存大小:Optional(512000)
*/

.default,默認(rèn)模式,系統(tǒng)會創(chuàng)建一個(gè)持久化的緩存并在用戶鑰匙串中存儲證書
.ephemeral,系統(tǒng)沒有持久化存儲,所有內(nèi)容的生命周期都與session相同,當(dāng)session無效時(shí)所有內(nèi)容自動釋放
.background(withIdentifier identifier: String),創(chuàng)建一個(gè)可以在后臺甚至APP已經(jīng)關(guān)閉的時(shí)候仍然在傳輸數(shù)據(jù)的會話,默認(rèn)是掛起狀態(tài)

  • 實(shí)現(xiàn)后臺下載與進(jìn)度打印
  1. 創(chuàng)建session會話
  2. 根據(jù)url創(chuàng)建dataTask
  3. 取消掛起狀態(tài),resume()
        let configuration3 = URLSessionConfiguration.background(withIdentifier: self.createID())
        
        let session = URLSession.init(configuration: configuration3, delegate: self, delegateQueue: OperationQueue.main)
        
        session.downloadTask(with: url).resume()
  1. 代理回調(diào)delegate
//ViewController
extension ViewController:URLSessionDownloadDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("下載完成-\(location)")
        let locationPath = location.path
        //取得新地址,文件以當(dāng)前時(shí)間的時(shí)間戳命名
        let documents = NSHomeDirectory() + "/Documents" + self.stringFromNow() + ".mp4"
        print("新地址:\(documents)")
        //移動文件
        let fileManager = FileManager.default
        try! fileManager.moveItem(atPath: locationPath, toPath: documents)
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print("下載進(jìn)度:\(totalBytesWritten/totalBytesExpectedToWrite)")
    }
}
  1. 申請后臺下載權(quán)限,AppDelegate設(shè)置回調(diào)CompletionHandler
//AppDelegate設(shè)置回調(diào)
    var backgroundSessionCompletionHandler: (() -> Void)?

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        self.backgroundSessionCompletionHandler = completionHandler
    }
  1. AppDelegate的回調(diào)completionHandler執(zhí)行
    從handleEventsForBackgroundURLSession方法的官方解釋(option+方法查看官方解釋)中知道

completionHandler
The completion handler to call when you finish processing the events. Calling this completion handler lets the system know that your app’s user interface is updated and a new snapshot can be taken.

因此,在AppDelegate設(shè)置的回調(diào)completionHandler需要在下載完成后在URLSessionDownloadDelegate執(zhí)行,告訴系統(tǒng)執(zhí)行完畢可以回收并刷新UI,避免影響系統(tǒng)運(yùn)行性能

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("后臺任務(wù)下載完成后回來")
        DispatchQueue.main.async {
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandler = appDelegate.backgroundSessionCompletionHandler else { return }
            backgroundHandler()
        }
    }

二、Http:三次握手四次揮手

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容