How to read a simple string from a POST request in AFNetworking (No JSON)

Haiku Oezu picture Haiku Oezu · Jan 9, 2014 · Viewed 11.2k times · Source

I'm using AFNetworking to communicate with a server through POST that responds with a simple string containing the information I need. I'm using the following code:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST: MY_URL
   parameters: MY_PARAMETERS
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //do something
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //etc.
      }];

However, it seems that AFNetworking expects every response to be in JSON format because I get this error when I execute my request:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x1566eb00 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

How can I tell AFNetworking that it's OK that the response is not a JSON object? I've seen something involving AFHTTPClient, but it doesn't seem to be part of AFNetworking anymore.

Answer

Rob picture Rob · Jan 9, 2014

You can tell the AFHTTPRequestOperationManager or AFHTTPSessionManager how to handle the response, e.g. before calling POST, you can do the following:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Then in your success block, you can convert the NSData to a string:

NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

Having said that, you might want to contemplate converting your web service to return JSON response, as it's far easier to parse that way (and differentiate between a valid response and some server error).