2

我按照文档中的建议将 AFHTTPClient 实现为单例类,并在帖子中使用 JSON 数据调用它,并接收 JSON 数据作为回报:

[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"my return is: %@", [responseObject valueForKeyPath:@"Result"]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {            
    NSLog(@"error in network call: %@", [error localizedDescription]);
}];

一切都很好,但是如果我收到一个错误,(“HTTPRequestOperation 中的错误:(200-299)中的预期状态代码,得到 400”),我实际上也在这里读取 responseObject(这是 API 的方式我正在使用告诉我我造成了哪类错误)。

我可以使用 AFJSONRequestOperation 做到这一点:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"my return is: %@", [JSON valueForKeyPath:@"Result"]);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"exception code: %@", [JSON valueForKeyPath:@"ExceptionCode"]);
    NSLog(@"exception message: %@", [JSON valueForKeyPath:@"ExceptionMessage"]);
}];
[operation start];

我如何(并且我可以?)使用 AFHTTPClient 来做到这一点?

4

2 回答 2

1

operation变量具有您需要的一切:

[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
  // ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    if ([operation isKindOfClass:[AFJSONRequestOperation class]]) {
      id JSON = [(AFJSONRequestOperation *)operation responseJSON];
      NSLog(@"JSON: %@", JSON)
    }
}];
于 2012-06-09T13:43:34.410 回答
-1

All credit goes to @phix23, who pointed me in the correct direction!

Here is the custom method I wrote in my subclassed AFHTTPClient that allows me to see the JSON response after receiving a 400 error:

- (void) myPostPath:(NSString *)path
        parameters:(NSDictionary *)parameters
           success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 
           failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
    NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];   
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];
}

I call it by:

[[BMNetworkCalls sharedInstance] myPostPath:theURL parameters:theDict success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
    NSLog(@"my return is: %@", [responseObject valueForKeyPath:@"Result"]);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {          
    NSLog(@"exception code: %@", [JSON valueForKeyPath:@"ExceptionCode"]);
}];
于 2012-06-08T00:00:08.500 回答