自定义序列化在Alamofire 4.0中找到不正确的“响应”

时间:2016-09-26 21:31:18

标签: swift alamofire swift3

我正在尝试为Alamofire 4.0定义自定义模型序列化。到目前为止,我正在关注responseJson和朋友们使用的模型。具体来说,到目前为止我所拥有的是:

extension Alamofire.Request {
    public static func serializeResponseModel<T:ModelObject>(response:HTTPURLResponse?, data:Data?, error:Error?) -> Alamofire.Result<T> {
        switch serializeResponseJSON(options: [], response: response, data: data, error: error) {
        case .success(let jsonObject):
            do {
                return .success(try T(json:jsonObject as! JSONObject))
            }
            catch {
                return .failure(error)
            }
        case .failure(let error):
            return .failure(error)
        }
    }
}

extension Alamofire.DataRequest {
    public static func serializeResponseModel<T:ModelObject>() -> DataResponseSerializer<T> {
        return DataResponseSerializer { _, response, data, error in
            return Request.serializeResponseConcierge(response: response, data: data, error: error)
        }
    }

    @discardableResult
    public func responseModel<T:ModelObject>(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self
    {
        return response(
            queue: queue,
            responseSerializer: DataRequest.serializeResponseModel(),
            completionHandler: completionHandler
        )
    }
}

不幸的是,框架实现得有些糟糕,而且return response(行找到response属性(在Request中定义)而不是相应的response方法(在DataRequest),这导致编译错误:

Cannot call value of non-function type 'HTTPURLResponse?'

我在这里错过了什么允许它在responseJson情况下工作,但不是在我的情况下?

1 个答案:

答案 0 :(得分:0)

显然问题是由于过度泛化而导致编译器无法为DataRequest.serializeResponseModel()生成适当的类型当我将responseModel更改为以下内容并指定了相应的类型时,事情按预期工作:

@discardableResult
public func responseModel<T:ModelObject>(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self
{
    return response(
        queue: queue,
        responseSerializer: DataRequest.modelResponseSerializer() as DataResponseSerializer<T>,
        completionHandler: completionHandler
    )
}