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

11,294

Solution 1

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).

Solution 2

  NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

you can get response description details like below

 NSLog(@"JSON: %@", [responseObject description]);
Share:
11,294

Related videos on Youtube

Haiku Oezu
Author by

Haiku Oezu

Updated on October 08, 2022

Comments

  • Haiku Oezu
    Haiku Oezu over 1 year

    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.

  • Haiku Oezu
    Haiku Oezu over 10 years
    Wonderful, this is just what I needed