iOS NSURLSession做HTTP请求

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

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

import UIKit
import Foundation

class LLNetwork: NSObject {
      func request(method: String, url: String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),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<String, AnyObject> = Dictionary<String, AnyObject>()) -> 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)