我使用AFNetwoking v 2.2.4作为iOS上的网络库。它将非http 2xx(http 200为成功)响应视为错误,并抛出错误块,如下所示:
NSError *error= nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error:&error];
NSString *connectionString = [NSString stringWithFormat:@"%@%@",SERVER_URL, RESOURCE_URL_USER_SIGNUP];
NSURL *url = [NSURL URLWithString:connectionString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"response object: %@", (NSDictionary *)responseObject);
[delegate userSignUpCompletedWithResponse:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
[delegate userSignUpFailedWithError:error];
NSString *errorBodyMessage = [[error userInfo] objectForKey:@"NSLocalizedRecoverySuggestion"];
NSLog(@"error message: %@", errorBodyMessage);
}];
[operation start];
这里,当http响应为200时,一切都按预期工作。我在服务器端有一个REST API,用ROR编写。对于用户注册,如果所有字段都有有效值,则它会发送200状态,但如果数据无效,例如已经采取电子邮件;在这种情况下,服务器发送422状态,并在JSON中显示错误消息。我需要跟踪错误消息并将其显示给移动用户,但我无法在错误块中获取消息对象。我记录了整个错误,但没有找到从服务器返回的对象。如果使用AFNetworking存在非2xx http响应,如何获取JSON对象?
答案 0 :(得分:3)
访问传递给失败块的responseObject
的{{1}}属性。
operation