Eric Chuang
Eric Chuang

Reputation: 1017

How can I post with a HTTP body properly?

I have a method in iOS where all I'm trying to do is to perform a POST with a simple NSDictionary in HTTP Body. Here is what I return with rac_POST.

return [[[self rac_POST:[NSString stringWithFormat:@"reservations/%@/update",reservationID] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
   [formData appendPartWithHeaders:@{@"Content-Type":@"application/json"} body:jsonData];
   [formData appendPartWithFormData:jsonData name:@"payload"];

}] map:^id(RACTuple *t) {
    RACTupleUnpack(NSDictionary * result) = t;
    return result;
}] catch:^RACSignal *(NSError *error) {
       return [self customErrorSignal:error];
}];

I've tried so many ways but it's just not POSTING through my API properly. I am converting my NSDictionary to NSData like this:

NSMutableDictionary *payloadDict = [[NSMutableDictionary alloc]init];
[payloadDict setObject:payloadArray forKey:@"payload"];
NSData *jsonData = [NSKeyedArchiver archivedDataWithRootObject:payloadDict];

What am I missing in my method?

I've also tried adding the body (payloadDict in my code above) to my parameters dictionary and it did not work. According to our internal API documents, it specifically said to add the payloadDict as part of the HTTP Body. Can someone also clarify if this makes a difference at all?

Upvotes: 0

Views: 109

Answers (2)

Ketan Parmar
Ketan Parmar

Reputation: 27438

If Your service accept json format of data then you should use NSJSONSerialization to convert root object to data instead of NSKeyedArchiver.

Upvotes: 0

kirti Chavda
kirti Chavda

Reputation: 3015

You can convert NSDictionary to NSData using this way

NSData  *jsonData = [NSJSONSerialization  dataWithJSONObject:questionDict options:0 error:nil];

Upvotes: 1

Related Questions