Swift Alamofire 到 return SwiftyJSON 结果的扩展方法
Swift extension method for Alamofire to return SwiftyJSON result
我将应用程序从 Swift 2.2 迁移到 3.0,它使用 GitHub 上 Alamofire-SwiftyJSON 项目的扩展方法。 Alamofire-SwiftyJSON 允许接收来自转换为 SwiftyJSON 实例的 Alamofire 网络请求的响应,如下所示:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.responseSwiftyJSON({ (request, response, json, error) in
print(json) // json is a SwiftyJSON 'JSON' instance
print(error)
})
在撰写此问题时,Alamofire-SwiftyJSON 项目尚未针对 Swift 3 进行更新。我正在寻找与 Swift 3+ 和 Alamofire 4+ 一起使用的 responseSwiftyJSON
扩展方法的等效实现。
扩展方法
此解决方案结合了 SwiftyJSON readme.
中关于使用 Alamofire 的建议
它基于 ResponseSerialization.swift 中 Alamofire 包含的类似扩展:
DataRequest.responseJSON(queue:options:completionHandler:)
DataRequest.jsonResponseSerializer(options:)
此解决方案适用于 Swift 3 及更高版本。它使用 Alamofire 4.2+ 和 SwiftyJSON 3.1.3+ 进行了测试。
import Alamofire
import SwiftyJSON
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseSwiftyJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<JSON>) -> Void) -> Self {
return response(
queue: queue,
responseSerializer: DataRequest.swiftyJSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
/// Creates a response serializer that returns a SwiftyJSON instance result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A SwiftyJSON response serializer.
public static func swiftyJSONResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<JSON> {
return DataResponseSerializer { _, response, data, error in
let result = Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
switch result {
case .success(let value):
return .success(JSON(value))
case .failure(let error):
return .failure(error)
}
}
}
}
使用示例:
Alamofire.request("https://httpbin.org/get").validate().responseSwiftyJSON {
response in
print("Response: \(response)")
switch response.result {
case .success(let json):
// Use SwiftyJSON instance
print("JSON: \(json)")
case .failure(let error):
// Handle error
print("Error: \(error)")
}
}
我将应用程序从 Swift 2.2 迁移到 3.0,它使用 GitHub 上 Alamofire-SwiftyJSON 项目的扩展方法。 Alamofire-SwiftyJSON 允许接收来自转换为 SwiftyJSON 实例的 Alamofire 网络请求的响应,如下所示:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.responseSwiftyJSON({ (request, response, json, error) in
print(json) // json is a SwiftyJSON 'JSON' instance
print(error)
})
在撰写此问题时,Alamofire-SwiftyJSON 项目尚未针对 Swift 3 进行更新。我正在寻找与 Swift 3+ 和 Alamofire 4+ 一起使用的 responseSwiftyJSON
扩展方法的等效实现。
扩展方法
此解决方案结合了 SwiftyJSON readme.
中关于使用 Alamofire 的建议它基于 ResponseSerialization.swift 中 Alamofire 包含的类似扩展:
DataRequest.responseJSON(queue:options:completionHandler:)
DataRequest.jsonResponseSerializer(options:)
此解决方案适用于 Swift 3 及更高版本。它使用 Alamofire 4.2+ 和 SwiftyJSON 3.1.3+ 进行了测试。
import Alamofire
import SwiftyJSON
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseSwiftyJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<JSON>) -> Void) -> Self {
return response(
queue: queue,
responseSerializer: DataRequest.swiftyJSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
/// Creates a response serializer that returns a SwiftyJSON instance result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A SwiftyJSON response serializer.
public static func swiftyJSONResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<JSON> {
return DataResponseSerializer { _, response, data, error in
let result = Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
switch result {
case .success(let value):
return .success(JSON(value))
case .failure(let error):
return .failure(error)
}
}
}
}
使用示例:
Alamofire.request("https://httpbin.org/get").validate().responseSwiftyJSON {
response in
print("Response: \(response)")
switch response.result {
case .success(let json):
// Use SwiftyJSON instance
print("JSON: \(json)")
case .failure(let error):
// Handle error
print("Error: \(error)")
}
}