iOS 进阶开发Swift开发进阶Alamofire

Alamofire-URLSession必备技能

2019-08-15  本文已影响18人  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初始化有三种模式:

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. 设置缓存策略

7. 支持后台转移

7. 支持自定义协议

8. 支持多路径TCP

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

10. 支持连接变化

三、NSURLRequestCachePolicy

OK,整理完毕!希望读者能够对URLSession更了解一些!

就问此时此刻还有谁?45度仰望天空,该死!我这无处安放的魅力!

上一篇下一篇

猜你喜欢

热点阅读