
安装
- 手动安装
- 下载Alamofire
- 将
Alamofire.xcodeproj
拖进到项目中

- 在**“Embedded Binaries**中添加

- command + B 编译后就可以使用
https://httpbin.org/ 网站可用来做http的各种请求测试使用,不过遗憾的是没有POST等提交类型请求的测试

基本使用
一个简单的请求:
1
2
3
|
import Alamofire
Alamofire.request("https://httpbin.org/get")
|
http中有请求(Request) 和 **响应(Response)**两个重要概念。大部分http框架,都会使用request
和response
作为方法名。
看看Alamofire的request
方法的详细参数:
1
2
3
4
5
6
7
8
|
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
|
有url
,method
,parameters
,encoding
,headers
五个参数,与http是相互对应的。其中只有url
是必须的,其它都有默认值。
请求后的响应处理
向http发送请求后,就需对响应结果进行处理。** Alamofire采用链式调用的方式处理响应,这种链式调用的方式最初应该是起源jQuery**。
响应处理的一般形式如下,response
就是响应结果。
1
2
3
|
Alamofire.request("https://httpbin.org/get").responseJSON { response in
}
|
Alamofire 提供了五种不同的响应处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
// Response Handler - Unserialized Response
func response(
queue: DispatchQueue?,
completionHandler: @escaping (DefaultDataResponse) -> Void)
-> Self
// Response Data Handler - Serialized into Data
func responseData(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Data>) -> Void)
-> Self
// Response String Handler - Serialized into String
func responseString(
queue: DispatchQueue?,
encoding: String.Encoding?,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
// Response JSON Handler - Serialized into Any
func responseJSON(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
// Response PropertyList (plist) Handler - Serialized into Any
func responsePropertyList(
queue: DispatchQueue?,
completionHandler: @escaping (DataResponse<Any>) -> Void))
-> Self
|
五种方法的参数不同,但最后一参数都是一个回调的闭包,都可以写成尾随闭包形式。除了response
方法的回调参数是DefaultDataResponse
,其它都是DataResponse
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public struct DataResponse<Value> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The result of response serialization.
public let result: Result<Value>
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
var _metrics: AnyObject?
|
DataResponse
与DefaultDataResponse
最大的不同就是多了两个属性result
和value
,value
值就是格式化的不同类型。
响应处理的一些例子
response
1
2
3
4
5
6
7
8
9
|
Alamofire.request("https://httpbin.org/get").response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
|
response
方法的响应结果response
是DefaultDataResponse
,没有进行过格式化处理。
responseData
1
2
3
4
5
6
7
|
Alamofire.request("https://httpbin.org/get").responseData { response in
debugPrint("All Response Info: \(response)")
if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
|
responseData
方法对响应结果进行了处理,response.result.value
就是我们属性的Data
类型。
- 链式调用
1
2
3
4
5
6
7
|
Alamofire.request("https://httpbin.org/get")
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
|
响应验证
http响应结果中的不同状态码(100..<600
)表示不同结果。
HTTP不同请求方式
request
方法的method
参数表示不同的方法。
1
2
3
4
5
|
Alamofire.request("https://httpbin.org/get") // method defaults to `.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
的参数按照固定格式写到URL中,其他类型则按照不同格式写到请求body中。
1
2
3
4
5
6
7
8
|
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
|
-
POST参数编码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
|
-
JSON编码
1
2
3
4
5
6
7
8
9
10
11
12
|
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
// Both calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
|
添加请求HTTP头部
1
2
3
4
5
6
7
8
|
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
debugPrint(response)
}
|
HTTP认证
1
2
3
4
5
6
7
8
|
let user = "user"
let password = "password"
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
|
下载文件
1
2
3
4
5
|
Alamofire.download("https://httpbin.org/image/png").responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
|
另外可以下文件保存在本地:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download("https://httpbin.org/image/png", to: destination).response { response in
print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
self.imageView.image = image
self.tableView.reloadData()
}
}
|
上传
1
2
3
4
5
|
let imageData = UIImagePNGRepresentation(image!)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
|
请求中花费的各种时间
1
2
3
|
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.timeline)
}
|
结果:
1
|
Timeline: { "Latency": 1.527 secs, "Request Duration": 1.528 secs, "Serialization Duration": 0.001 secs, "Total Duration": 1.529 secs }
|
文章作者
andyron
上次更新
2024-07-16
许可协议
原创文章,如需转载请注明文章作者和出处。谢谢!