Alamofire network

Alamofire鏈接

Alamofire是一個純粹的網絡庫,關於UI的部分有另外的封裝,比如AlamofireImage
AlamofireNetworkActivityIndicator

一、URLSession

步驟

  1. 創建session會話
  2. 根據url創建dataTask
  3. 取消掛起狀態,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內存大小:\(String(describing: configuration1.urlCache?.memoryCapacity))")
        
        let configuration2 = URLSessionConfiguration.ephemeral
        print("configuration2沙盒大小:\(String(describing: configuration2.urlCache?.diskCapacity))")
        print("configuration2內存大小:\(String(describing: configuration2.urlCache?.memoryCapacity))")

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

.default,默認模式,系統會創建一個持久化的緩存並在用戶鑰匙串中存儲證書
.ephemeral,系統沒有持久化存儲,所有內容的生命週期都與session相同,當session無效時所有內容自動釋放
.background(withIdentifier identifier: String),創建一個可以在後臺甚至APP已經關閉的時候仍然在傳輸數據的會話,默認是掛起狀態

  • 實現後臺下載與進度打印
  1. 創建session會話
  2. 根據url創建dataTask
  3. 取消掛起狀態,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. 代理回調delegate
//ViewController
extension ViewController:URLSessionDownloadDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("下載完成-\(location)")
        let locationPath = location.path
        //取得新地址,文件以當前時間的時間戳命名
        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("下載進度:\(totalBytesWritten/totalBytesExpectedToWrite)")
    }
}
  1. 申請後臺下載權限,AppDelegate設置回調CompletionHandler
//AppDelegate設置回調
    var backgroundSessionCompletionHandler: (() -> Void)?

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        self.backgroundSessionCompletionHandler = completionHandler
    }
  1. AppDelegate的回調completionHandler執行
    從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設置的回調completionHandler需要在下載完成後在URLSessionDownloadDelegate執行,告訴系統執行完畢可以回收並刷新UI,避免影響系統運行性能

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章