Alamofire-从URLSession说起

2019-08-15  本文已影响0人  SPIREJ

转自Cooci_和谐学习_不急不躁 感谢作者的辛勤付出🤙🤙🤙

Alamofire是一个为iOSmacOS打造的并基于Swift的网络库。它在Apple的基础网络架构上提供了更加优雅的接口来简化繁重而常用的网络请求任务。
Alamofire提供了链式的request/response方法,JSON的传参和响应序列化,身份认证和其他特性。
Alamofire的优雅之处在于它完完全全是由Swift写成的,并且没有从它的Objective-C版本AFNetworking那继承任何特性。

因为我们的Alamofire是对苹果URLSession的封装,所以在探索Alamofire之前,我们来看看URLSession的必备基础

一、请求网络的基本格式

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

二、URLSessionConfiguration

1、三种模式

URLSessionConfiguration初始化有三种模式:

default:默认模式,通常我们用这种模式就足够了。default模式下系统会创建一个持久化的缓存并在用户的钥匙串中存储证书
ephemeral: 系统没有任何持久性存储,所有内容的生命周期都与session相同,当session无效时,所有内容自动释放。

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

打印结果:
沙盒大小: Optional(10000000)
内存大小: Optional(512000)
沙盒大小: Optional(0)
内存大小: Optional(512000)
// 初始化一个后台的模式的会话配置
let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
// 初始化session会话
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
// 传入url开启下载
session.downloadTask(with: url).resume()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
易错易忽略点

上面这么设置,还不能达到后台下载!还需要设置下面两步

//用于保存后台下载的completionHandler
var backgroundSessionCompletionHandler: (() -> Void)?

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    self.backgroundSessionCompletionHandler = completionHandler
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    print("后台任务下载回来")
    DispatchQueue.main.async {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
        backgroundHandle()
    }
}

为什么这么处理,苹果爸爸说的算

2、 常规属性

3、设置Cookie政策

4、设置安全策略

5、设置缓存策略

6、支持后台转移

7、支持自定义协议

8、支持多路径TCP

9、设置HTTP策略和代理属性

10、支持连接变化

三、NSURLRequestCachePolicy

总结

最后放一张脑图总结URLSession

上一篇下一篇

猜你喜欢

热点阅读