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:三次握手四次挥手

你可能感兴趣的:(Alamofire network)