확장 메서드
이 솔루션은 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는 대기열이 실행중인 스레드에서 호출되거나 대기열이 nil 인 경우 주 스레드에서 호출됩니다. responseSerializer는 Alamofire 내부의 NSOperationQueue에서 호출됩니다. SWiftyJSON readme처럼 validate()에 대한 호출을 추가 할 것입니다. – Heliotropix
피드백 @ user992167 주셔서 감사합니다! 제안한대로 validate() 메서드를 추가했습니다. –