手把手教你封裝一個簡單的iOS HTTP請求

前言

最近在研究AFN的實(shí)現(xiàn)方式,發(fā)現(xiàn)它使用block替代了代理的方式,將各個網(wǎng)絡(luò)請求的各個階段都整合在一起,使得代碼更加簡潔易讀,于是我也參照它的方式嘗試用swift封裝了一個基于NSURLSession的網(wǎng)絡(luò)請求,實(shí)現(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
/** 下載進(jìn)度回調(diào) */
typealias DownloadProgressBlock = (NSURLSessionDownloadTask, bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void
/** 上傳進(jìn)度回調(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?

實(shí)例化一個manager對象,用它來做所有的網(wǎng)絡(luò)請求操作,外部也是通過manager來調(diào)用請求方法,同時創(chuàng)建一個session實(shí)例

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)
}

簡單請求

先來實(shí)現(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
}

//實(shí)現(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!
}

下載請求

實(shí)現(xiàn)下載請求比較復(fù)雜一些,代理方法中的參數(shù)需要傳遞出來,同時因?yàn)閟ession是一個異步操作,有時需要等待某些數(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
}

接下來就是幾個代理方法中的處理,有一點(diǎn)需要注意,由于succeedHandler需要拿到responseObjerror兩個參數(shù)分別是在

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)

這兩個不同的代理方法中,所以我這里的處理是在didFinishDownloadingToURL方法中將得到的responseObj用一個全局變量存起來,然后使用隊(duì)列組的等待功能再在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!
}

實(shí)現(xiàn)最后一個下載進(jì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)")
})

實(shí)現(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容