从 iOS7 开始,苹果推出了 URLSession ,在 OC 中叫 NSURLSession,取代了 URLConnection。因为 Alamofire 底层也是封装的 URLSession,因此咱们先来了解一下原生的 URLSession,再来学习 Alamofire 会更加透彻。若是朋友们已经对 URLSession 掌握的很好了,那么能够跳过此篇。swift
建立 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
缘由在于 configure 有三种类型:网络
.default
: 是默认的值,这和 URLSession.shared 建立的 session 是同样的,可是比起这个单例,它能够进行更多的扩展配置。.ephemeral
:ephemeral
和 URLSession.shared 很类似,区别是 不会写入 caches, cookies 或 credentials(证书)到磁盘。.background
: 后台 session,能够在程序切到后台、崩溃或未运行时进行上传和下载。
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()
:取消任务
自从有了 URLSession ,iOS 才真正实现了后台下载。下面是一个简单的后台下载的实现。async
let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
复制代码
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
复制代码
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
}
}
复制代码
还须要在主线程中回调系统回调,告诉系统及时更新屏幕
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!
以上的总结参考了并部分摘抄了如下文章,很是感谢如下做者的分享!:
二、Cooci的《Alamofire-URLSession必备技能》
转载请备注原文出处,不得用于商业传播——凡几多