Alamofire是一個純粹的網(wǎng)絡(luò)庫饭玲,關(guān)于UI的部分有另外的封裝侥祭,比如AlamofireImage
和AlamofireNetworkActivityIndicator
一、URLSession
步驟
- 創(chuàng)建session會話
- 根據(jù)url創(chuàng)建dataTask
- 取消掛起狀態(tài)茄厘,resume()
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil {
print("請求成功 \(String(describing: response))")
}
}.resume()
URLSession的三種configuration
let configuration1 = URLSessionConfiguration.default
print("configuration1沙盒大小:\(String(describing: configuration1.urlCache?.diskCapacity))")
print("configuration1內(nèi)存大小:\(String(describing: configuration1.urlCache?.memoryCapacity))")
let configuration2 = URLSessionConfiguration.ephemeral
print("configuration2沙盒大小:\(String(describing: configuration2.urlCache?.diskCapacity))")
print("configuration2內(nèi)存大小:\(String(describing: configuration2.urlCache?.memoryCapacity))")
/*
打印結(jié)果:
configuration1沙盒大小:Optional(10000000)
configuration1內(nèi)存大小:Optional(512000)
configuration2沙盒大小:Optional(0)
configuration2內(nèi)存大小:Optional(512000)
*/
.default矮冬,默認(rèn)模式,系統(tǒng)會創(chuàng)建一個持久化的緩存并在用戶鑰匙串中存儲證書
.ephemeral次哈,系統(tǒng)沒有持久化存儲胎署,所有內(nèi)容的生命周期都與session相同,當(dāng)session無效時所有內(nèi)容自動釋放
.background(withIdentifier identifier: String)窑滞,創(chuàng)建一個可以在后臺甚至APP已經(jīng)關(guān)閉的時候仍然在傳輸數(shù)據(jù)的會話琼牧,默認(rèn)是掛起狀態(tài)
- 實現(xiàn)后臺下載與進(jìn)度打印
- 創(chuàng)建session會話
- 根據(jù)url創(chuàng)建dataTask
- 取消掛起狀態(tài),resume()
let configuration3 = URLSessionConfiguration.background(withIdentifier: self.createID())
let session = URLSession.init(configuration: configuration3, delegate: self, delegateQueue: OperationQueue.main)
session.downloadTask(with: url).resume()
- 代理回調(diào)delegate
//ViewController
extension ViewController:URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("下載完成-\(location)")
let locationPath = location.path
//取得新地址哀卫,文件以當(dāng)前時間的時間戳命名
let documents = NSHomeDirectory() + "/Documents" + self.stringFromNow() + ".mp4"
print("新地址:\(documents)")
//移動文件
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath, toPath: documents)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print("下載進(jìn)度:\(totalBytesWritten/totalBytesExpectedToWrite)")
}
}
- 申請后臺下載權(quán)限巨坊,AppDelegate設(shè)置回調(diào)CompletionHandler
//AppDelegate設(shè)置回調(diào)
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
self.backgroundSessionCompletionHandler = completionHandler
}
- AppDelegate的回調(diào)completionHandler執(zhí)行
從handleEventsForBackgroundURLSession方法的官方解釋(option+方法查看官方解釋)中知道
completionHandler
The completion handler to call when you finish processing the events. Calling this completion handler lets the system know that your app’s user interface is updated and a new snapshot can be taken.
因此,在AppDelegate設(shè)置的回調(diào)completionHandler需要在下載完成后在URLSessionDownloadDelegate執(zhí)行此改,告訴系統(tǒng)執(zhí)行完畢可以回收并刷新UI趾撵,避免影響系統(tǒng)運行性能
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
print("后臺任務(wù)下載完成后回來")
DispatchQueue.main.async {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let backgroundHandler = appDelegate.backgroundSessionCompletionHandler else { return }
backgroundHandler()
}
}