擴展方法
該解決方案結合了來自SwiftyJSON readme與Alamofire工作的建議。
它是基於在ResponseSerialization.swift附帶Alamofire類似擴展:
DataRequest.responseJSON(queue:options:completionHandler:)
DataRequest.jsonResponseSerializer(options:)
該溶液可與夫特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)")
}
}
粗糙的,但優雅一旦你明白Alamofire做。 completionHandler在隊列正在運行的線程或主線程上被調用,如果隊列爲零。 responseSerializer在Alamofire內部的NSOperationQueue被調用。我會在SWiftyJSON自述文件中添加一個對validate()的調用。 – Heliotropix
感謝您的反饋@ user992167!我按照你的建議添加了validate()方法。 –