最基本的GET请求
Alamofire.request("xxx")
我们也可以直接获得json数据
简单了解一下JSON https://www.jianshu.com/p/30873633912a
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // 最初的 url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // 序列化 result
if let json = response.result.value {
print("JSON: \(json)") // 打印json
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
这个被各种教程推荐的库 支持多种返回序列化数据的方法
response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
请求时的一些细节
方法默认为 .get
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
GET Request With URL-Encoded Parameters
let parameters: Parameters = ["foo": "bar"]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default`
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))
// https://httpbin.org/get?foo=bar
网友评论