Alamofire 学习(二)-URLSession 知识准备

843 阅读4分钟

一、简介

iOS7 开始,苹果推出了 URLSession ,在 OC 中叫 NSURLSession,取代了 URLConnection。由于 Alamofire 底层也是封装的 URLSession,所以我们先来了解一下原生的 URLSession,再来学习 Alamofire 会更加透彻。如果朋友们已经对 URLSession 掌握的很好了,那么可以跳过此篇。

二、URLSession 请求

1、请求的基本流程

创建 configurations ➡️ 创建 session ➡️ 创建 task ➡️ resume() 开始请求➡️ 监听回调

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

上面是 URLSession 的一个最基本的请求格式,其中 URLSession.shared 为我们提供了一个单例 session 对象,它为创建任务提供了默认配置。 其中省略了configurations 的设置,其实上面的代码也可以详细展开写成下面这样:

let configure = URLSessionConfiguration.default
let session = URLSession.init(configuration: configure)
session.dataTask(with: url) { (data, response, error) in
    if error == nil {
        print("请求成功\(String(describing: response))" )
    }
}.resume()

URLSession 可以通过 URLSessionConfiguration 创建 URLSession 实例。为什么第一部分代码是可以省略configure 的呢?

URLSessionConfiguration:

原因在于 configure 有三种类型:

  • .default 是默认的值,这和 URLSession.shared 创建的 session 是一样的,但是比起这个单例,它可以进行更多的扩展配置。
  • .ephemeral ephemeralURLSession.shared 很相似,区别是 不会写入 caches, cookiescredentials(证书)到磁盘。
  • .background 后台 session,可以在程序切到后台、崩溃或未运行时进行上传和下载。

URLSessionTask:

URLSessionTask 是一个表示任务对象的抽象类,一个会话(session)创建一个任务(task),这里任务是指获取数据、下载或上传文件。 task 任务有四种类型:

  • URLSessionDataTask:处理从HTTP get请求中从服务器获取数据到内存中。
  • URLSessionUploadTask:上传硬盘中的文件到服务器,一般是HTTP POST 或 PUT方式
  • URLSessionDownloadTask:从远程服务器下载文件到临时文件位置。
  • NSURLSessionStreamTask:基于流的URL会话任务,提供了一个通过 NSURLSession 创建的 TCP/IP 连接接口。

任务操作

注意:我们的网络任务默认是挂起状态的(suspend),在获取到 dataTask 以后需要使用 resume() 函数来恢复或者开始请求。

  • resume():启动任务
  • suspend():暂停任务
  • cancel():取消任务

2、后台下载

自从有了 URLSessioniOS 才真正实现了后台下载。下面是一个简单的后台下载的实现。

1、初始化一个 background 的模式的 configuration

let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())

2、通过 configuration 初始化网络下载会话,设置相关代理,回调数据信号响应。

let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

3、session 创建 downloadTask 任务- resume 启动

session.downloadTask(with: url).resume()

4、发起连接 - 发送相关请求 - 回调代理响应

  • 下载进度 的代理回调 urlSession(_ session: downloadTask:didWriteData bytesWritten: totalBytesWritten: totalBytesExpectedToWrite: ) 来监听下载进度:
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")
}

由于 http 的分片传输,所以下载进度是隔一段时间回调一次的。

  • 下载完成 的代理回调 didFinishDownloadingTo,实现下载完成转移临时文件里的数据到相应沙盒保存
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // 下载完成 - 开始沙盒迁移
    print("下载完成 - \(location)")
    let locationPath = location.path
    // 拷贝到用户目录(文件名以时间戳命名)
    let documnets = NSHomeDirectory() + "/Documents/" + self.lgCurrentDataTurnString() + ".mp4"
    print("移动地址:\(documnets)")
    //创建文件管理器
    let fileManager = FileManager.default
    try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
}

5、开启后台下载权限

除了这些,想要实现后台下载还必须在 AppDelegate 中实现 handleEventsForBackgroundURLSession,开启后台下载权限:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    //用于保存后台下载的completionHandler
    var backgroundSessionCompletionHandler: (() -> Void)?
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        self.backgroundSessionCompletionHandler = completionHandler
    }
}

6、在 urlSessionDidFinishEvents 中回调系统回调

还需要在主线程中回调系统回调,告诉系统及时更新屏幕

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    print("后台任务下载回来")
    DispatchQueue.main.async {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
        backgroundHandle()
    }
}

⚠️ 如果不实现这个代理里面的回调函数,依然可以实现后台下载,但会出现卡顿的问题,控制台也会出现警告。

Warning: Application delegate received call to - application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.

URLSession 的基础知识就先复习到这,下一篇就来正式学习一下 Alamofire

以上的总结参考了并部分摘抄了以下文章,非常感谢以下作者的分享!:

1、思绪_HY的《URLSession基本使用》

2、Cooci的《Alamofire-URLSession必备技能》

转载请备注原文出处,不得用于商业传播——凡几多