前言
最近在研究AFN的实现方式,发现它使用block替代了代理的方式,将各个网络请求的各个阶段都整合在一起,使得代码更加简洁易读,于是我也参照它的方式尝试用swift封装了一个基于NSURLSession
的网络请求,实现了一些简单功能。
知识准备
在此之前有必要了解一些关于NSURLSession
的相关知识,我在iOS网络-NSURLSession简单使用中简单总结了一些,更详细的资料可以看看URL Session Programming Guide
需要用到的
首先是请求方式,使用枚举表示,分别对应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"
}
再下来就是需要定义几个用到的闭包类型
/** 请求成功的回调 */
typealias SucceedHandler = (NSData?, NSURLResponse?) -> Void
/** 请求失败的回调 */
typealias FailedHandler = (NSURLSessionTask?, NSError?) -> Void
/** 下载进度回调 */
typealias DownloadProgressBlock = (NSURLSessionDownloadTask, bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void
/** 上传进度回调 */
typealias UploadProgressBlock = (NSURLSessionDownloadTask, bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void
/** 完成下载回调 */
typealias FinishDownloadBlock = (NSURLSessionDownloadTask, distinationURL: NSURL) -> Void
/** 完成任务回调 */
typealias CompletionBlock = (NSURLSessionTask, responseObj:AnyObject?, error: NSError?) -> Void
在类中声明几个闭包变量,用于在代理方法中存储参数,以便于回调
var successHandler:SucceedHandler?
var failHandler:FailedHandler?
var downloadProgressHandler:DownloadProgressBlock?
var uploadProgressHandler:UploadProgressBlock?
var finishHandler:FinishDownloadBlock?
var completionHandler:CompletionBlock?
实例化一个manager
对象,用它来做所有的网络请求操作,外部也是通过manager
来调用请求方法,同时创建一个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)
}
简单请求
先来实现一个简单的请求,也就是使用GET获取json或者xml数据之后解析这类的,可以在请求成功和失败之后做一些做一些操作,其主要用到的是:
public func dataTaskWithRequest(request: NSURLRequest,
completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
核心思路还是将原先在completionHandler
里面的回调传递出来:
//创建一个请求
func createRequest(URLString:String, method:Method) -> (NSMutableURLRequest){
let request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
request.HTTPMethod = method.rawValue
return request
}
//实现方法
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!
}
下载请求
实现下载请求比较复杂一些,代理方法中的参数需要传递出来,同时因为session是一个异步操作,有时需要等待某些数据返回之后才将其传递出来,否则就会出现莫名其妙的结果。
先将回调方法用全局变量保存起来,在代理方法中传递参数
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中根据返回的error
是否为空来决定是否调用succeedHandler
回调:
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
两个参数分别是在
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
和
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
这两个不同的代理方法中,所以我这里的处理是在didFinishDownloadingToURL
方法中将得到的responseObj
用一个全局变量存起来,然后使用队列组的等待功能再在didCompleteWithError
方法中的回调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!
}
实现最后一个下载进度的回调
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)
}
}
具体应用
简单封装之后,使用简单请求的时候就十分便捷了,不需要重写一堆的代理方法,只需要在写好请求成功和失败的操作就行了:
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)")
})
实现下载文件功能:
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