Alamofire 的同步请求
Swift 3.0+,iOS 9.0+,Mac OS X 10.11+,tvOS 9.0+,watchOS 2.0+
Xcode 8.0+
对于 Alamofire 4.0+
pod 'Alamofire-Synchronous', '~> 4.0'
对于 Alamofire 3.0+
pod 'Alamofire-Synchronous', '~> 3.0'
如果您从主队列执行同步请求
同步请求执行完成后主队列中的以下任务将被延迟执行(包括 UI 更新),因为您同时从主队列执行了同步请求。另一方面,在 Alamofire 4 中,新增加了 downloadProgress
和 uploadProgress
方法的参数 queue
,其默认值为 DispatchQueue.main
,因此,您需要将新增加参数的值设置为非主队列。
示例
// from the main queue (**not recommended**):
let response = Alamofire.download("https://httpbin.org/stream/100", method: .get, to: destination).downloadProgress { progress in
// Codes at here will be delayed before the synchronous request finished running.
print("Download Progress: \(progress.fractionCompleted)")
}.response()
if let error = response.error {
print("Failed with error: \(error)")
}else{
print("Downloaded file successfully")
}
// from the main queue (**not recommended**):
let response = Alamofire.download("https://httpbin.org/stream/100", method: .get, to: destination).downloadProgress(queue: DispatchQueue.global(qos: .default)) { progress in
// Codes at here will not be delayed
print("Download Progress: \(progress.fractionCompleted)")
DispatchQueue.main.async {
// code at here will be delayed before the synchronous finished.
}
}.response()
if let error = response.error {
print("Failed with error: \(error)")
}else{
print("Downloaded file successfully")
}
import Alamofire
import Alamofire_Synchronous
Alamofire 和 Alamofire_Synchronous 之间的用法差异:在响应*方法中,只需简单地使用响应*方法返回的值来移除 queue
和 completionHandler
参数。
示例(Alamofire 4.0+)
//get request and response json
let response = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON()
if let json = response.result.value {
print(json)
}
// post request and response json(with default options)
let response = Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["foo": "bar"]).responseJSON(options: .allowFragments)
if let json = response.result.value {
print(json)
}
// download
let response = Alamofire.download("https://httpbin.org/stream/100", method: .get, to: destination).response()
if let error = response.error {
print("Failed with error: \(error)")
}else{
print("Downloaded file successfully")
}
有关更多用法,请参阅 Alamofire 的文档。
有关详细信息,请参阅 LICENSE。