Alamofire的Swift扩展方法返回SwiftyJSON结果

时间:2017-01-23 06:11:19

标签: ios swift alamofire swifty-json

我将应用程序从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)
    })

在写这个问题时,没有为Swift 3更新Alamofire-SwiftyJSON项目。我正在寻找适用于Swift 3+和Alamofire 4 +的responseSwiftyJSON扩展方法的等效实现。

1 个答案:

答案 0 :(得分:4)

扩展方法

此解决方案包含了从SwiftyJSON readme开始使用Alamofire的建议。

它基于Alamofire在ResponseSerialization.swift中包含的类似扩展程序:

  • 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)")
        }
    }