AFNetworking 2.0 AFHTTPSessionManager:如何在故障块中获取状态代码和响应JSON? [英] AFNetworking 2.0 AFHTTPSessionManager: how to get status code and response JSON in failure block?
问题描述
切换到AFNetworking 2.0时,AFHTTPClient已由AFHTTPRequestOperationManager/AFHTTPSessionManager替换(如迁移指南中所述).使用AFHTTPSessionManager时遇到的第一个问题是如何在故障块中检索响应的正文?
When switched to AFNetworking 2.0 the AFHTTPClient has been replaced by AFHTTPRequestOperationManager / AFHTTPSessionManager (as mentioned in the migration guide). The very first issue I came across when using the AFHTTPSessionManager is how to retrieve the body of the response in the failure block?
这是一个例子:
[self.sessionManager POST:[endpoint absoluteString] parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
// How to get the status code?
} failure:^(NSURLSessionDataTask *task, NSError *error) {
// How to get the status code? response?
}];
在成功块中,我想检索响应的状态代码. 在故障块中,我想同时检索响应的状态代码和内容(在本例中为JSON,它描述了服务器端错误).
In the success block I would like to retrieve response's status code. In the failure block I would like to retrieve both response's status code and the content (which is JSON in this case that describes the server-side error).
NSURLSessionDataTask具有NSURLResponse类型的响应属性,该属性没有statusCode字段.目前,我能够像这样检索statusCode:
The NSURLSessionDataTask has a response property of type NSURLResponse, which has not statusCode field. Currently I'm able to retrieve statusCode like this:
[self.sessionManager POST:[endpoint absoluteString] parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
// How to get the status code?
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
DDLogError(@"Response statusCode: %i", response.statusCode);
}];
但这对我来说很难看.而且仍然无法确定响应的主体.
But this looks ugly to me. And still can't figure about the response's body.
有什么建议吗?
推荐答案
您可以使用"AFNetworkingOperationFailingURLResponseDataErrorKey"键直接从AFNetworking中访问数据"对象,因此无需子类化AFJSONResponseSerializer.您可以将数据序列化为可读的字典. 这是获取JSON数据的一些示例代码:
You can access the "data" object directly from AFNetworking by using the "AFNetworkingOperationFailingURLResponseDataErrorKey" key so there is no need for subclassing the AFJSONResponseSerializer. You can the serialize the data into a readable dictionary. Here is some sample code to get JSON Data :
NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
以下是在失败"块中获取状态代码的代码:
Here is the code to Get Status code in the Failure block:
NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
NSLog( @"success: %d", r.statusCode );
这篇关于AFNetworking 2.0 AFHTTPSessionManager:如何在故障块中获取状态代码和响应JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!