基于NSURLSession 封裝的網絡請求:HttpRequestSwift

jopen 9年前發布 | 9K 次閱讀 Apple Swift開發 HttpRequestSwift

基于NSURLSession 封裝的網絡請求 使用簡單 支持多種請求方式

我建議網絡層是以Delegate為主,Notification為輔。原因如下:

盡可能減少跨層數據交流的可能,限制耦合統一回調方法,便于調試和維護在跟業務層對接的部分只采用一種對接手段(在我這兒就是只采用delegate這一個手段)限制靈活性,以此來交換應用的可維護性

然后我們順便來說說為什么盡量不要用block。 block很難追蹤,難以維護我們在調試的時候經常會單步追蹤到某一個地方之后,發現尼瑪這里有個block,如果想知道這個block里面都做了些什么事情,這時候就比較蛋疼了。 block會延長相關對象的生命周期 block會給內部所有的對象引用計數加一,這一方面會帶來潛在的retain cycle,不過我們可以通過Weak Self的手段解決。另一方面比較重要就是,它會延長對象的生命周期。

在網絡回調中使用block,是block導致對象生命周期被延長的其中一個場合,當ViewController從window中卸下時,如果尚有請求帶著block在外面飛,然后block里面引用了ViewController(這種場合非常常見),那么ViewController是不能被及時回收的,即便你已經取消了請求,那也還是必須得等到請求著陸之后才能被回收。

然而使用delegate就不會有這樣的問題,delegate是弱引用,哪怕請求仍然在外面飛,,ViewController還是能夠及時被回收的,回收之后指針自動被置為了nil,無傷大雅。

所以平時盡量不要濫用block,尤其是在網絡層這里。

引用iOS架構師的話,基于NSURLSesson封裝了一套Delegate回調的請求方法,目前只支持GET,POST,持續更新中.

基本使用方法

let info = HttpRequestInfo(url: "http://www.baidu.com", delegate: self)

      info.sendRequest()

或者你也可以這樣

let info = HttpRequestInfo(url: "http://www.baidu,com", delegate: self, state: XUDataRequestState.post)
    info.httpBody = body


    let helper = HttpRequestHelper.sharedHelper()

    helper.sandAsyncHttpRequest(info)

消息會從代理回調

func requestSuccess(data: AnyObject, operation: NSHTTPURLResponse) {

   let datastr = try? NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.PrettyPrinted)
    let jsonstr: String = NSString(data: datastr!, encoding: NSUTF8StringEncoding) as! String
    let popTime = dispatch_time(DISPATCH_TIME_NOW,Int64(1 * Double(NSEC_PER_SEC)))
    dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
      let alert =  UIAlertController(title: "請求成功", message: jsonstr, preferredStyle: UIAlertControllerStyle.Alert)
      self.presentViewController(alert, animated: true, completion: nil)
    }
    print(operation.statusCode)

}
func requestFailed(error: NSError?) {
    print(error)
}

可以從Model模型中拿取數據方便管理

class func loadFirstData(delegate:HttpRequestLoadDataProtocol) -> Void{

    let info = HttpRequestInfo(url: "123", delegate: delegate)


    info.sendRequest()


}

class func loadSecondData(delegate:HttpRequestLoadDataProtocol) -> Void{

    let info = HttpRequestInfo(url: "234", delegate: delegate)


    info.sendRequest()


}

調用方法

TestModel.loadFirstData(self)
  TestModel.loadSecondData(self)

項目主頁:http://www.baiduhome.net/lib/view/home/1442815676013

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!