Search code examples
iosobjective-cjsonpostafnetworking

AFNetworking - Make an HTTP POST to REST, sending a JSON with Base64string image


I am trying to send a base64 encoded image among some other strings using http POST and AFNetworking. I am trying to send the parameters as an NSDictionary:

  NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [info setValue:filedata forKey:@"filedata"];
    [info setValue:comments forKey:@"comments"];
    [info setValue:username forKey:@"username"];
    [info setValue:@"jpg" forKey:@"filetype"];
    [info setValue:filename forKey:@"filename"];

and POST using AFNetworking:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    [manager POST:@"https://myurl.com/fileupload" parameters:info progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

However I am not sure what else to do at this point. What am I missing? Thank you


Solution

  • You can use the following example

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:@"https://myurl.com/fileupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"key name for the image"
                                fileName:photoName mimeType:@"image/jpeg"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"Response: %@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"Error: %@", error);
    }];