Alamofire.request("https://httpbin.org/get").responseJSON { (response) in
// original url request
print("Request: \(String(describing: response.request))")
// http url response
print("Response: \(String(describing: response.response))")
// response serialization result
print("Result: \(response.result)")
if let json = response.result.value {
print("JSON:\(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
Alamofire.request("https://httpbin.org/get").responseString { (response) in
print("Response String: \(String(describing: response.result.value))")
}.responseJSON { (response) in
print("Response JSON:\(String(describing: response.result.value)")
}
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
let headers: HTTPHeaders = [
"Accept" : "application/json",
"Authorization" : "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers)
/**
默认情况下,响应处理是在主线程执行,也可以自定义
*/
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue, options: []) { (response) in
print("Executing response handler on utility queue")
}
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { (response) in
switch response.result {
case .success:
print("successful")
case .failure:
print("error")
}
Alamofire.download("https://httpbin.org/image/png")
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
let imageData = UIImagePNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")!
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
.uploadProgress { progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
}
.downloadProgress { progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
}