Search code examples
iosafnetworkingafnetworking-2

Objective-C How to POST form-data using AFNetworking?


I have a webservice and I can successfully make post calls to it via Postman utility. On Postman the settings arePostman settings

I am unable to make the same call using Afnetworking using code.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"body": @{@"email":@"[email protected]",@"name":@"myName"}};
[manager POST:@"http://myURL.com/user" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

My guess is that I am not setting the form-data correctly?


Solution

  • You need to serialize your params dictionary and then string encode it, since your body parameter has a JSON object in it. Try using this :

        NSDictionary *params = @{@"email": @"[email protected]", @"name": @"myName"};
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSDictionary *dict = @{@"body":json};
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        [manager POST:@"http://myURL.com/user" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSString *myString = [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding];
            NSLog(@"Error: %@", myString);
        }];