Alamofire的错误序列化程序

时间:2014-12-23 22:22:51

标签: ios swift alamofire

我正在尝试为Alamofire编写通用序列化程序,我正在尝试理解如何使通用响应序列化程序确定是否存在错误并返回自定义错误对象(服务器返回错误字典)情况)。

任何意见都会受到赞赏!

以下是我目前使用的示例代码:

@objc public protocol ResponseObjectSerializable {
    init?(response: NSHTTPURLResponse, representation: AnyObject)
}

extension Alamofire.Request {
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                        return (T(response: response!, representation: JSON!), nil)
                    } else {
                        return (nil, serializationError)
                    }
                }

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
            completionHandler(request, response, object, error)
        })
    }
}

0 个答案:

没有答案