ResponseSerializer'无法使用Swift 3

时间:2016-08-17 18:28:25

标签: ios swift alamofire swift3 swifty-json

在更新到Xcode 8 beta 6之前,我一直在使用以下代码。它类似于Alamofire存储库中的this example。今天早上我将我的Alamofire库更新到最新的swift3分支,该分支现在与beta 6兼容。它显示错误:Cannot call value of non-function type 'HTTPURLResponse?'类似的问题存在here,但它不是基于关于当前版本的Swift和Alamofire。

根据我的理解,这个错误是因为它认为我试图返回Request属性response而不是函数response(responseSerializer: <T>, completionHandler: <(Response<T.SerializedObject, T.ErrorObject>) -> Void>)而它认为这是因为类型错误在我传入函数的responseSerializercompletionHandler中。

如何调整此代码以使其与函数声明和编译器兼容?

我将@escaping添加到completionHandler以更正错误。

import Foundation
import Alamofire
import SwiftyJSON

extension Alamofire.Request {
public func responseObject<T: ResponseJSONObjectSerializable>(_ completionHandler: @escaping (Response<T, NSError>) -> Void) -> Self {
    let responseSerializer = ResponseSerializer<T, NSError> { request, res, data, error in

        guard let responseData = data else {
            let error = DFError.error(withDFCode: .dataSerializationFailed, failureReason: "Data could not be serialized because input data was nil.")
            return .failure(error)
        }

        let jsonData: Any?
        do {
            jsonData = try JSONSerialization.jsonObject(with: responseData, options: [])
        } catch  {
            let error = DFError.error(withDFCode: .jsonSerializationFailed, failureReason: "JSON could not be serialized into response object")
            return .failure(error)
        }

        let json = SwiftyJSON.JSON(jsonData!)
        if let newObject = T(json: json) {

            return .success(newObject)
        }

        let error = DFError.error(withDFCode: .jsonSerializationFailed, failureReason: "JSON could not be serialized into response object")
        return .failure(error)
    }

    return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
    //Error: Cannot call value of non-function type 'HTTPURLResponse?'
}
}

2 个答案:

答案 0 :(得分:8)

您需要将completionHandler标记为@escaping

答案 1 :(得分:3)

即使将@escaping添加到闭包中,我仍然会看到此错误。我遇到的问题是我需要将我的扩展声明从extension Alamofire.Request { }更改为extension Alamofire.DataRequest { }