Alamofire-URLSession介绍

2019-08-16  本文已影响0人  May_Dobin

一.URLSesstion

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error == nil {
                print("请求成功\(String(describing: response))" )
            }
        }.resume()

创建session会话对象
创建dataTask网络任务
开启resume任务

二. URLSessionConfiguration

1. 三种模式
open class URLSessionConfiguration : NSObject, NSCopying {
    open class var `default`: URLSessionConfiguration { get }
    open class var ephemeral: URLSessionConfiguration { get }
    @available(iOS 8.0, *)
    open class func background(withIdentifier identifier: String) -> URLSessionConfiguration
Default sessions behave much like the shared session (unless you customize them further), but let you obtain data incrementally using a delegate. You can create a default session configuration by calling the default method on the URLSessionConfiguration class.

Ephemeral sessions are similar to default sessions, but they don’t write caches, cookies, or credentials to disk. You can create an ephemeral session configuration by calling the ephemeral method on the URLSessionConfiguration class.

Background sessions let you perform uploads and downloads of content in the background while your app isn’t running. You can create a background session configuration by calling the backgroundSessionConfiguration(_:) method on the URLSessionConfiguration class.
  • default是最常用的默认模式,该模式下系统会创建一个持久化的缓存,同时将证书存储在用户的钥匙串中
  • ephemeral除了没有存储外,和default差不多
  • background后台运行模式,可以使APP在没运行的时候,通过调用backgroundSessionConfiguration(_:),实现上传和下载
        let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())

        let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
        
        session.downloadTask(with: url).resume()
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("下载完成 - \(location)")
    }
    
    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")
    }
2.常规属性
3. 设置Cookie政策
4. 设置安全策略
5. 设置缓存策略
6. 支持后台转移
7. 支持自定义协议
8. 支持多路径TCP
9. 设置HTTP策略和代理属性
10. 支持连接变化

三.NSURLRequestCachePolicy

上一篇下一篇

猜你喜欢

热点阅读