2017-01-09 711 views
2

我只是在玩Alamofire框架,并且没有多少API调用。但我观察到alamofire有两种请求方法:Alamofire的responseJSON和responseData之间的区别

responseJSON和responseData of Alamofire有什么区别。

public func responseData(
    queue: DispatchQueue? = nil, 
    completionHandler: @escaping (DataResponse<Data>) -> Void) 
    -> Self 
{ 
    return response(
     queue: queue, 
     responseSerializer: DataRequest.dataResponseSerializer(), 
     completionHandler: completionHandler 
    ) 
} 




public func responseJSON(
    queue: DispatchQueue? = nil, 
    options: JSONSerialization.ReadingOptions = .allowFragments, 
    completionHandler: @escaping (DataResponse<Any>) -> Void) 
    -> Self 
{ 
    return response(
     queue: queue, 
     responseSerializer: DataRequest.jsonResponseSerializer(options: options), 
     completionHandler: completionHandler 
    ) 
} 

回答

3

responseJSON将传递一个JSON对象到它的完成。即它将是具有String键和JSON兼容值的字典或数组。

responseData将通过一个Data对象到其完成。这可能包含可以反序列化为JSON对象的JSON数据,但它也可能包含任何其他类型的数据。图像数据,HTML,视频数据等...

如果您知道您从端点获取JSON,请使用responseJSON调用。

+0

谢谢!我知道了 ! –

+0

我不确定您是否使用名为'SwiftJSON'的库。只是想问,如果我使用这样一个库,是否可以一直使用'responseData'?因为我的API集合中有一个特定的端点返回一个错误,指出JSON不能被解析或者使用'responseJSON'。 – Glenn

+1

@ prettyitgirl.com如果数据是无效的JSON那么你会得到那个错误。如果响应中使用json,则只使用responseJSON。如果没有,你可以使用responseData,它只会传递给你原始数据(例如它可能是一个文件或其他类型的数据)。 – Fogmeister

相关问题