Swift_网络请求

一 第一种:导入第三方

import Alamofire//网络请求
import SwiftyJSON//数据解析

1,参数为value

let dic = []
Alamofire.request(.POST,"", parameters:dic)
.responseJSON {response in
    if let Error = response.result.error{
        print(Error,"")
    }else if let value = response.result.value{
        let json = JSON(value)
        print(json)
    }
}

2,参数为body

let dic = []
Alamofire.request(.POST,"", parameters:dic, encoding: .JSON)
.responseJSON {response in
    if let Error = response.result.error{
        print(Error,"")
    }else if let value = response.result.value{
        let json = JSON(value)
        print(json)
    }
}

二 第二种:不需要导入第三方

    let parameter = []
    do {
        let body = try! NSJSONSerialization.dataWithJSONObject(parameter, options: NSJSONWritingOptions.PrettyPrinted)
        let request = NSMutableURLRequest(URL: NSURL(string: "")!)
        request.HTTPBody = body
        request.HTTPMethod = "POST"
        //设置json格式
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
            let value : AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.AllowFragments)
            print(value)
//            let json = JSON(value)
//            print(json)
        }
        task.resume()
    }

你可能感兴趣的:(Swift_网络请求)