原文出自:www.hangge.com 轉(zhuǎn)載請(qǐng)保留原文鏈接:http://www.hangge.com/blog/cache/detail_780.html
URLSession 類支持三種類型的任務(wù):加載數(shù)據(jù)颜启、下載和上傳偷俭。下面通過(guò)樣例分別進(jìn)行介紹。(本文代碼已升級(jí)至 Swift3)
1缰盏,使用Data Task加載數(shù)據(jù)
使用全局的 URLSession.shared 和 dataTask 方法創(chuàng)建涌萤。
func sessionLoadData(){
//創(chuàng)建URL對(duì)象
let urlString = "http://hangge.com"
let url = URL(string:urlString)
//創(chuàng)建請(qǐng)求對(duì)象
let request = URLRequest(url: url!)
let session = URLSession.shared
let dataTask = session.dataTask(with: request,
completionHandler: {(data, response, error) -> Void in
if error != nil{
print(error.debugDescription)
}else{
let str = String(data: data!, encoding: String.Encoding.utf8)
print(str)
}
}) as URLSessionTask
//使用resume方法啟動(dòng)任務(wù)
dataTask.resume()
}
2,使用Download Task來(lái)下載文件
(1)不需要獲取進(jìn)度
使用全局的 URLSession.shared 和 downloadTask 方法即可
func sessionSimpleDownload(){
//下載地址
let url = URL(string: "http://hangge.com/blog/images/logo.png")
//請(qǐng)求
let request = URLRequest(url: url!)
let session = URLSession.shared
//下載任務(wù)
let downloadTask = session.downloadTask(with: request,
completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
-> Void in
//輸出下載文件原來(lái)的存放目錄
print("location:\(location)")
//location位置轉(zhuǎn)換
let locationPath = location!.path
//拷貝到用戶目錄
let documnets:String = NSHomeDirectory() + "/Documents/1.png"
//創(chuàng)建文件管理器
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
print("new location:\(documnets)")
})
//使用resume方法啟動(dòng)任務(wù)
downloadTask.resume()
}
(2)實(shí)時(shí)獲取進(jìn)度
需要使用自定義的 URLSession 對(duì)象和 downloadTask 方法
import UIKit
class ViewController: UIViewController, URLSessionDownloadDelegate {
private lazy var session:URLSession = {
//只執(zhí)行一次
let config = URLSessionConfiguration.default
let currentSession = URLSession(configuration: config, delegate: self,
delegateQueue: nil)
return currentSession
}()
override func viewDidLoad() {
super.viewDidLoad()
sessionSeniorDownload()
}
//下載文件
func sessionSeniorDownload(){
//下載地址
let url = URL(string: "http://hangge.com/blog/images/logo.png")
//請(qǐng)求
let request = URLRequest(url: url!)
//下載任務(wù)
let downloadTask = session.downloadTask(with: request)
//使用resume方法啟動(dòng)任務(wù)
downloadTask.resume()
}
//下載代理方法口猜,下載結(jié)束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
//下載結(jié)束
print("下載結(jié)束")
//輸出下載文件原來(lái)的存放目錄
print("location:\(location)")
//location位置轉(zhuǎn)換
let locationPath = location.path
//拷貝到用戶目錄
let documnets:String = NSHomeDirectory() + "/Documents/2.png"
//創(chuàng)建文件管理器
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
print("new location:\(documnets)")
}
//下載代理方法形葬,監(jiān)聽(tīng)下載進(jìn)度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
//獲取進(jìn)度
let written:CGFloat = (CGFloat)(totalBytesWritten)
let total:CGFloat = (CGFloat)(totalBytesExpectedToWrite)
let pro:CGFloat = written/total
print("下載進(jìn)度:\(pro)")
}
//下載代理方法,下載偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
//下載偏移暮的,主要用于暫停續(xù)傳
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
3笙以,使用Upload Task來(lái)上傳文件
func sessionUpload(){
//上傳地址
let url = URL(string: "http://hangge.com/upload.php")
//請(qǐng)求
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = "POST"
let session = URLSession.shared
//上傳數(shù)據(jù)流
let documents = NSHomeDirectory() + "/Documents/1.png"
let imgData = try! Data(contentsOf: URL(fileURLWithPath: documents))
let uploadTask = session.uploadTask(with: request, from: imgData) {
(data:Data?, response:URLResponse?, error:Error?) -> Void in
//上傳完畢后
if error != nil{
print(error)
}else{
let str = String(data: data!, encoding: String.Encoding.utf8)
print("上傳完畢:\(str)")
}
}
//使用resume方法啟動(dòng)任務(wù)
uploadTask.resume()
}