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

前言

最近在研究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需要拿到responseObjerror兩個參數(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末铛只,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子糠溜,更是在濱河造成了極大的恐慌淳玩,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件诵冒,死亡現(xiàn)場離奇詭異凯肋,居然都是意外死亡,警方通過查閱死者的電腦和手機汽馋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進店門侮东,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人豹芯,你說我怎么就攤上這事悄雅。” “怎么了铁蹈?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵宽闲,是天一觀的道長。 經(jīng)常有香客問我握牧,道長容诬,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任沿腰,我火速辦了婚禮览徒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘颂龙。我一直安慰自己习蓬,他們只是感情好纽什,可當(dāng)我...
    茶點故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著躲叼,像睡著了一般芦缰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上枫慷,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天让蕾,我揣著相機與錄音,去河邊找鬼流礁。 笑死涕俗,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的神帅。 我是一名探鬼主播再姑,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼找御!你這毒婦竟也來了元镀?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤霎桅,失蹤者是張志新(化名)和其女友劉穎栖疑,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體滔驶,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡遇革,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了揭糕。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片萝快。...
    茶點故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖著角,靈堂內(nèi)的尸體忽然破棺而出揪漩,到底是詐尸還是另有隱情,我是刑警寧澤吏口,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布奄容,位于F島的核電站,受9級特大地震影響产徊,放射性物質(zhì)發(fā)生泄漏昂勒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一舟铜、第九天 我趴在偏房一處隱蔽的房頂上張望叁怪。 院中可真熱鬧,春花似錦深滚、人聲如沸奕谭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽血柳。三九已至,卻和暖如春生兆,著一層夾襖步出監(jiān)牢的瞬間难捌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工鸦难, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留根吁,地道東北人。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓合蔽,卻偏偏與公主長得像击敌,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子拴事,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容