前言
最近在研究AFN的實現(xiàn)方式厕鹃,發(fā)現(xiàn)它使用block替代了代理的方式疾牲,將各個網(wǎng)絡(luò)請求的各個階段都整合在一起,使得代碼更加簡潔易讀曼氛,于是我也參照它的方式嘗試用swift封裝了一個基于NSURLSession
的網(wǎng)絡(luò)請求豁辉,實現(xiàn)了一些簡單功能。
知識準(zhǔn)備
在此之前有必要了解一些關(guān)于NSURLSession
的相關(guān)知識舀患,我在iOS網(wǎng)絡(luò)-NSURLSession簡單使用中簡單總結(jié)了一些徽级,更詳細(xì)的資料可以看看URL Session Programming Guide
需要用到的
首先是請求方式,使用枚舉表示,分別對應(yīng)get聊浅,post等多種方式:
enum Method:String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
再下來就是需要定義幾個用到的閉包類型
/** 請求成功的回調(diào) */
typealias SucceedHandler = (NSData?, NSURLResponse?) -> Void
/** 請求失敗的回調(diào) */
typealias FailedHandler = (NSURLSessionTask?, NSError?) -> Void
/** 下載進度回調(diào) */
typealias DownloadProgressBlock = (NSURLSessionDownloadTask, bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void
/** 上傳進度回調(diào) */
typealias UploadProgressBlock = (NSURLSessionDownloadTask, bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void
/** 完成下載回調(diào) */
typealias FinishDownloadBlock = (NSURLSessionDownloadTask, distinationURL: NSURL) -> Void
/** 完成任務(wù)回調(diào) */
typealias CompletionBlock = (NSURLSessionTask, responseObj:AnyObject?, error: NSError?) -> Void
在類中聲明幾個閉包變量,用于在代理方法中存儲參數(shù)灰追,以便于回調(diào)
var successHandler:SucceedHandler?
var failHandler:FailedHandler?
var downloadProgressHandler:DownloadProgressBlock?
var uploadProgressHandler:UploadProgressBlock?
var finishHandler:FinishDownloadBlock?
var completionHandler:CompletionBlock?
實例化一個manager
對象,用它來做所有的網(wǎng)絡(luò)請求操作狗超,外部也是通過manager
來調(diào)用請求方法,同時創(chuàng)建一個session
實例
var session:NSURLSession?
lazy var myQueue:NSOperationQueue = {
let q = NSOperationQueue()
q.maxConcurrentOperationCount = 1
return q
}()
internal static let manager:AHNetworkingManager = {
let m = AHNetworkingManager()
return m
}()
override init() {
super.init()
session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: myQueue)
}
簡單請求
先來實現(xiàn)一個簡單的請求,也就是使用GET獲取json或者xml數(shù)據(jù)之后解析這類的朴下,可以在請求成功和失敗之后做一些做一些操作努咐,其主要用到的是:
public func dataTaskWithRequest(request: NSURLRequest,
completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
核心思路還是將原先在completionHandler
里面的回調(diào)傳遞出來:
//創(chuàng)建一個請求
func createRequest(URLString:String, method:Method) -> (NSMutableURLRequest){
let request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
request.HTTPMethod = method.rawValue
return request
}
//實現(xiàn)方法
func dataTask(method:Method, URLString:String, succeed:SucceedHandler?, failed:FailedHandler?) -> NSURLSessionDataTask {
let request = createRequest(URLString, method: method)
var task:NSURLSessionDataTask?
task = self.session!.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let e = error {
NSLog("fail with error:\\(e.localizedDescription)")
if let f = failed {
f(task,e)
}
return
}
if let s = succeed {
s(data, response)
}
}
return task!
}
下載請求
實現(xiàn)下載請求比較復(fù)雜一些,代理方法中的參數(shù)需要傳遞出來殴胧,同時因為session是一個異步操作渗稍,有時需要等待某些數(shù)據(jù)返回之后才將其傳遞出來佩迟,否則就會出現(xiàn)莫名其妙的結(jié)果。
先將回調(diào)方法用全局變量保存起來竿屹,在代理方法中傳遞參數(shù)
private func downloadTask(method:Method,URLString:String,
downloadProgress:DownloadProgressBlock?,uploadProgress:UploadProgressBlock?,
finish:FinishDownloadBlock?, completion:CompletionBlock?) -> NSURLSessionDownloadTask {
let request = createRequest(URLString, method: method)
let task = self.session!.downloadTaskWithRequest(request)
if let d = downloadProgress {
self.downloadProgressHandler = d
}
if let f = finish {
self.finishHandler = f
}
if let c = completion {
self.completionHandler = c
}
return task
}
在completion
這個block中根據(jù)返回的error
是否為空來決定是否調(diào)用succeedHandler
回調(diào):
private func downloadTask(method:Method,
URLString:String,
succeed:SucceedHandler?,
failed:FailedHandler?,
downloadProgress:DownloadProgressBlock?,
uploadProgress:UploadProgressBlock?,
finish:FinishDownloadBlock?) -> NSURLSessionDownloadTask {
let task = downloadTask(method,URLString: URLString,
downloadProgress: downloadProgress,uploadProgress: nil,
finish: finish,completion:{ (task,respobseObj:AnyObject?, error) -> Void in
if error != nil {
NSLog("fail with error:\\(error)")
if let f = failed {
f(task,error)
}
return
}
if let s = succeed {
s(respobseObj as? NSData,task.response)
}
})
return task
}
接下來就是幾個代理方法中的處理报强,有一點需要注意,由于succeedHandler
需要拿到responseObj
和error
兩個參數(shù)分別是在
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
和
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
這兩個不同的代理方法中拱燃,所以我這里的處理是在didFinishDownloadingToURL
方法中將得到的responseObj
用一個全局變量存起來秉溉,然后使用隊列組的等待功能再在didCompleteWithError
方法中的回調(diào)self.compleHandler
,
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(0, 0)
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
let distination = savePathForDownloadData(location, task: downloadTask)
NSLog("distination:\\(distination)")
if let finish = self.finishHandler {
finish(downloadTask, distinationURL: distination)
}
dispatch_group_async(group, queue) { () -> Void in
self.responseObj = NSData(contentsOfURL: distination)
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
dispatch_group_notify(group, queue) { () -> Void in
if let complete = self.completionHandler {
complete(task, responseObj: self.responseObj, error: error)
}
}
}
//MARK: save downloaded data then return save path
func savePathForDownloadData(location:NSURL, task:NSURLSessionDownloadTask) -> NSURL {
let manager = NSFileManager.defaultManager()
let docDict = manager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let originURL = task.originalRequest?.URL
let distinationURL = docDict?.URLByAppendingPathComponent((originURL?.lastPathComponent)!)
do{
try manager.removeItemAtURL(distinationURL!)
}catch{
NSLog("remove failed")
}
do{
try manager.copyItemAtURL(location, toURL: distinationURL!)
}catch{
NSLog("copy failed")
}
return distinationURL!
}
實現(xiàn)最后一個下載進度的回調(diào)
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let p = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
NSLog("progress:\\(p)")
if let progressHandler = self.downloadProgressHandler {
progressHandler(downloadTask,bytesWritten: bytesWritten,totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
}
具體應(yīng)用
簡單封裝之后碗誉,使用簡單請求的時候就十分便捷了召嘶,不需要重寫一堆的代理方法,只需要在寫好請求成功和失敗的操作就行了:
let manager = AHNetworkingManager.manager
manager.get(URLString, succeed: { (data:NSData?, response:NSURLResponse?) -> Void in
let arr = self.parseResponse(data!, response: response!)
for dic in arr {
let model = Model(dic: dic)
self.models.append(model)
}
dispatch_async(dispatch_get_main_queue(),{ Void in
self.tableView.reloadData()
})
}, failed: {(task,error) -> Void in
NSLog("請求失敗哮缺,reason:\\(error?.localizedDescription)")
})
實現(xiàn)下載文件功能:
let manager = AHNetworkingManager.manager
downloadTask = manager.get(URLString, finish: { (task, distinationURL) -> Void in
self.imgPath = distinationURL
assert(self.imgPath.absoluteString.characters.count>0, "imgPath is not exit")
NSLog("download completed in path:\\(self.imgPath)")
let data = NSData(contentsOfURL: self.imgPath)
let img = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.imageView.image = img
}
}, failed: {(task,error) -> Void in
NSLog("下載失敗弄跌,reason:\\(error?.localizedDescription)")
},downloadProgress: { (task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) -> Void in
let p = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.progress.text = "\\(p)"
self.progressBar.progress = p
}
NSLog("progress:\\(p)")
})
可以把這個小demo下下來跑看看,如果對你有幫助尝苇,還望不吝嗇你的star