iOS HTTP请求

没有容错处理,没有降耦合设计、接口多级封装等等的设计

原生NSURLSession做个http请求很简单啊(swif代码看的真心顺眼多了)

import UIKit
import Foundation

class LLNetwork: NSObject {
      func request(method: String, url: String, params: Dictionary = Dictionary(),callback: (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void) {
        //组装URL
        var newURL = url
        if method == "GET"{
            newURL += "?"
            newURL +=  self.buildParams(params)
        }
        //创建URLRequest 存储请求信息
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        request.HTTPMethod = method
        if method == "POST"{
            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = buildParams(params).dataUsingEncoding(NSUTF8StringEncoding)
        }
        
        //创建网络请求会话
        let task =  NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            callback(data: data, response: response , error: error)
        })
        task.resume()
    }
    
    //组合参数
    func buildParams(params: Dictionary = Dictionary()) -> String {
        var newURL = ""
        for (key,value) in params{
            newURL +=  (key + "=" + (value as! String) + "&")
        }
        newURL = newURL.substringToIndex(newURL.characters.indexOf(newURL.characters.last!)!)
        return newURL
    }
}

你可能感兴趣的:(网络通信,iOS,http,NSURLSession)