is there an example of AFHTTPClient posting json with AFNetworking?

20,493

Solution 1

If you're posting to a JSON REST API, there should be a particular mapping from object property to JSON key, right? That is, the server is expecting certain information in certain named fields.

So what you want to do is construct an NSDictionary or NSMutableDictionary with the keys used in the API and their corresponding values. Then, simply pass that dictionary into the parameters argument of any request method in AFHTTPClient. If the parameterEncoding property of the client is set to AFJSONParameterEncoding, then the body of the requests will automatically be encoded as JSON.

Solution 2

The best and simple way to do that is to subclass AFHTTPClient.

Use this code snippet

MBHTTPClient

#define YOUR_BASE_PATH @"http://sample.com"
#define YOUR_URL @"post.json"
#define ERROR_DOMAIN @"com.sample.url.error"

/**************************************************************************************************/
#pragma mark - Life and Birth

+ (id)sharedHTTPClient
{
    static dispatch_once_t pred = 0;
    __strong static id __httpClient = nil;
    dispatch_once(&pred, ^{
        __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:YOUR_BASE_PATH]];
        [__httpClient setParameterEncoding:AFJSONParameterEncoding];
        [__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
        //[__httpClient setAuthorizationHeaderWithUsername:@"" password:@""];
    });
    return __httpClient;
}

/**************************************************************************************************/
#pragma mark - Custom requests

- (void) post<#Objects#>:(NSArray*)objects
success:(void (^)(AFHTTPRequestOperation *request, NSArray *objects))success
failure:(void (^)(AFHTTPRequestOperation *request, NSError *error))failure
{
    [self postPath:YOUR_URL
       parameters:objects
          success:^(AFHTTPRequestOperation *request, id JSON){
              NSLog(@"getPath request: %@", request.request.URL);

              if(JSON && [JSON isKindOfClass:[NSArray class]])
              {
                  if(success) {
                      success(request,objects);
                  }
              }
              else {
                  NSError *error = [NSError errorWithDomain:ERROR_DOMAIN code:1 userInfo:nil];
                  if(failure) {
                      failure(request,error);
                  }
              }
          }
          failure:failure];
}

Then in your code just call

[[MBHTTPClient sharedHTTPClient]  post<#Objects#>:objects
                                          success:^(AFHTTPRequestOperation *request, NSArray *objects) {
    NSLog("OK");
}
                                          failure:(AFHTTPRequestOperation *request, NSError *error){
    NSLog("NOK %@",error);
}

objects is an NSArray (you can change it to NSDictonary) and will be encode in JSON format

Share:
20,493
MonkeyBonkey
Author by

MonkeyBonkey

CTO of Pictorious.com, a mobile app for turning photo sharing into a fun meme-game.

Updated on July 09, 2022

Comments

  • MonkeyBonkey
    MonkeyBonkey almost 2 years

    Looking for an example of how to post json with AFHTTPClient. I see that there is a postPath method which takes an NSDictionary and the AFJSONEncode method returns an NSData. Is there an easy way to serialize an object to NSDictionary, or is there an easier way using jsonkit?

    I just need to post the object as json to a REST API.

    UPDATE: So I tried passing a dictionary over but it seems to break on serializing a nested array.

    For example, if I have an object:

    Post* p = [[Post alloc] init];
    p.uname = @"mike";
    p.likes =[NSNumber numberWithInt:1];
    p.geo = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:37.78583], [NSNumber numberWithFloat:-122.406417], nil ];
    p.place = @"New York City";
    p.caption = @"A test caption";
    p.date = [NSDate date];
    

    who's get dictionary has data like the following:

    {
        caption = "A test caption";
        date = "2011-12-13 17:58:37 +0000";
        geo =     (
            "37.78583",
            "-122.4064"
        );
        likes = 1;
        place = "New York City";
    
    }
    

    the serialization will either just fail outright or geo will not be serialized as an array but as a string literal like ("37.78583", "-122.4064");

  • MonkeyBonkey
    MonkeyBonkey over 12 years
    Hey Matt, I was trying that earlier and had trouble with a nested nsarray. It seems to work fine until I it takes my geo property which is an NSArray of two NSNumbers. It will pass that as a quoted string with escaped characters so it is submitted as "(\n 43.1, \n -70.0)"
  • MonkeyBonkey
    MonkeyBonkey over 12 years
    Ok, so I was getting that funny formatting if I didn't set json serialization, but with json serialization I get an error in serializing the NSDate. Can I pass it a date formatter or should I format it to string in the dictionary before I pass it to AFNetworking?
  • MonkeyBonkey
    MonkeyBonkey over 12 years
    worked out serializing with jsonkit by passing in a block to handle NSDates into the JSONDataWithOptions method... what's the best way do you think to work that back into the afnetworking request?
  • mattt
    mattt over 12 years
    Be sure to use convert NSDate into an NSString with either a date formatter (check out ISO8601Formatter), or just by sending -description.
  • Tariq
    Tariq over 11 years
    Hey @mattt Can you please have a look on this question stackoverflow.com/questions/13219006/…
  • unspokenblabber
    unspokenblabber about 11 years
    @mattt once you add AFJSONParameterEncoding I am assuming AFN applies the encoding to every request, am I right? Can we have it applied to certain requests only ?
  • Thibaut LE LEVIER
    Thibaut LE LEVIER about 11 years
    doesn't seem to work with the latests versions of AFNetworking. postPath expect a NSDictionary as parameters.
  • RyanG
    RyanG about 11 years
    Worked like a charm. Thanks!
  • kleopatra
    kleopatra almost 11 years
    tried to format your code (not overly successful ;-) - please edit and improve