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

1、简介

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

2、URLSession 请求

一、请求的基本流程

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

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 的呢?cookie

URLSessionConfiguration:

缘由在于 configure 有三种类型:网络

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

URLSessionTask:

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

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

任务操做

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

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

二、后台下载

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

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

let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
复制代码

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

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

三、session 建立 downloadTask 任务- resume 启动

session.downloadTask(with: url).resume()
复制代码

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

  • 下载进度 的代理回调 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 的分片传输,因此下载进度是隔一段时间回调一次的。ide

  • 下载完成 的代理回调 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)
}
复制代码

五、开启后台下载权限

除了这些,想要实现后台下载还必须在 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
    }
}
复制代码

六、在 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

以上的总结参考了并部分摘抄了如下文章,很是感谢如下做者的分享!:

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

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

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

相关文章
相关标签/搜索