AFNetworking 3.0 multipart/form-data API call without file gives error

165 Views Asked by At

I am attaching the screenshot of Postman

enter image description here

Using postman I am getting successful response. But I am not able to get same response using AFNetworking library. Following is my sample code.

- (void)updateActivityQuantity:(NSDictionary *)quantityDic{
    NSString *strURL = [NSString stringWithFormat:@"%@/%@", MAINTAIN_BASEURL,JobDetailCommonURL];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSURLSessionTask *task = [manager POST:strURL parameters:quantityDic constructingBodyWithBlock:nil  progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } failure:^(NSURLSessionTask *task, NSError *error) {
        NSLog(@"error = %@", error);
    }];

    if (!task) {
        NSLog(@"Creation of task failed.");
    }
}

How can I successful response using AFNetworking?

1

There are 1 best solutions below

0
Mehedi Hasan On

You should not serialize your request manager for JSON. You can serialize your manager for multipart form-data like this

[manager.requestSerializer setValue:@"multipart/form-data; boundary=something" forHTTPHeaderField:@"Content-Type"]; 
manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 

And you need to serialize & encode your 'events' key's value as string if you didn't do it earlier like bellow, since it's a JSON object and add it to your quantityDic dictionary.

NSDictionary *events = @[@{@"event_time": @"564545454", ....}];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];