2012-06-07 109 views
2

我執行AFHTTPClient作爲一個單獨的類,如文檔建議,並呼籲與在後JSON數據,並接收返回JSON數據:接收與AFHTTPClient錯誤響應呼籲

[[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」),我實際上想要在這裏讀取響應對象(這是我使用的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呢?

+0

你應該在BMNetworkCalls中寫一個自定義方法對於每個API調用 – Felix

回答

1

operation

- (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]; 
} 

我通過把它變量有你需要的一切:

[[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) 
    } 
}]; 
+0

現在你告訴我..(咧嘴笑)。請注意,我的答案如下,即使不必要。 – coco

-1

所有功勞歸於@ phix23,他指出我的方向正確!

下面是自定義的方法我在子類AFHTTPClient寫道,讓我看到了JSON響應接收一個400錯誤後:

[[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"]); 
}]; 
+0

這是不必要的。您可以訪問通常在失敗回調模塊中傳遞的操作變量的responseJSON屬性。 – mattt