AFNetworking: Can't get the response string from AFHTTPRequestOperation

Hernan Arber picture Hernan Arber · Dec 11, 2012 · Viewed 19.8k times · Source

Anyone?): I'm having a problem that has made me scratch my head for the last 2 hours, and it most likely a very simple stupid thing I'm missing. I Keep getting a building error when I Call the response string from the operation @ AFNetworking... Like there is NO SUCH PROPERTY....

Please Take a look at my code and Explain me what did I Mess up This time :p.. THanks :)


NSDictionary* paramDict = [NSDictionary dictionaryWithObjectsAndKeys:WebServicemd5Value, WebSermd5Variable, nil]
;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:webServiceURL]];

[httpClient defaultValueForHeader:@"Accept"];

[httpClient postPath:@"method" parameters:paramDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response data: %@", responseObject);
    NSLog(@"Reponse String: %@", operation);

// Printing operation will show me the operation Dictionary, including the reponse field, // but when I Directly call operation.response, the Compiler won't Build, stating that // "Property not found for AFHTTPRequestOperation".... WEIRDEST THING EVER, right?

    NSString* responseString = [NSString stringWithUTF8String:[responseObject bytes]];
    //.. Rest o f my Code....

}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error retrieving data: %@", error);
}];

Answer

amb picture amb · Dec 13, 2012

Hernan, if you expect an NSDictionary from a JSON response you should consider using AFJSONRequestOperation, because you get a JSON dictionary in your success callback. Anyway, if you want to get a dictionary from your responseObject, try to use the following code:

NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if (error) {
    NSLog(@"Error serializing %@", error);
}
NSLog(@"Dictionary %@", JSON);