在Object-C中AFNetworking几乎是我们不可或缺的第三方库,使用起来非常方便,在Swift中,Alamofire是对应AFNetworking的第三方库,使用方法完全一样,下面看看常用的GET和POST怎么来写的:
新的Alamofire对请求做了改动如下:
var urlString = "https://httpbin.org/get"; Alamofire.request(urlString).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ] ] let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json" ] Alamofire.request(urlString, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (respond) in if let JSON = respond.result.value { print("JSON: \(JSON)") } }
以上为新改动后常用方法
func loadData() { Alamofire.request(.GET, "https://api.108tian.com/mobile/v3/SceneDetail?id=528b91c9baf6773975578c5c", parameters: nil).responseJSON() { response in if let dic = response.result.value { print("dic: \(dic)") } else { print("dic: \(response)") } } var headers:Dictionary = [String:String]() headers["Content-Type"] = "application/json" headers["Set-Cookie"] = "xxxxxxxxxxxxxxxxx" var dic = [String:AnyObject]() dic["id"] = "CodingFire" dic["passWord"] = "1234567890" Alamofire.request(.POST, "https://api.108tian.com/mobile/v3/SceneDetail?id=", parameters:dic , encoding: ParameterEncoding.JSON, headers: headers).responseJSON{ (response) in if let dic = response.result.value { print("dic: \(dic)") } else { print("dic: \(response)") } } }
这俩接口需要替换成你自己的,博主只是随便写下,亲测无误。
下一篇将介绍如何用Swift上传头像。