NSURLSession -- 实际开发中运用

NSURLSession实际请求

iOS9使用http请求方法:

  1. 在工程info.plist文件内添加NSAppTransportSecurity键,类型为dictionary
  2. 在NSAppTransportSecurity中添加NSAllowsArbitraryLoads键,值为YES

GET请求

        let key = "a27383fa93bd3cc57ff4a180036d56ac"
        let urlString = "http://v.juhe.cn/xianxing/citys"
        let url = NSURL(string: urlString + "?key=" + key)
        
        // 创建请求对象
        let request = NSURLRequest(URL: url!)
        
        // 获取会话对象
        let session = NSURLSession.sharedSession()
        
        // 创建请求任务
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            if let jsonData = data {
                do {
                    let dic = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? [String : AnyObject]
                    print(dic)
                } catch {
                    
                }
            }
        }
        
        // 执行任务
        task.resume()

POST请求

        let urlString = "http://v.juhe.cn/carzone/series/query"
        let url = NSURL(string: urlString)
        
        // 创建请求对象
        let request = NSMutableURLRequest(URL: url!)
        // 设置请求模式
        request.HTTPMethod = "POST"
        // 设置请求体
        request.HTTPBody = "action=getCarAllBrand&key=afdfb2885044bf2e14b24c293012bbea".dataUsingEncoding(NSUTF8StringEncoding)
        
        
        // 获取会话对象
        let session = NSURLSession.sharedSession()
        
        // 创建请求任务
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            if let jsonData = data {
                do {
                    let dic = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? [String : AnyObject]
                    print(dic)
                } catch {
                    
                }
            }
        }
        
        // 执行任务
        task.resume()
原文地址:https://www.cnblogs.com/Alex-sk/p/5574159.html