I want to upload an image from a dictionary which looks like this, { pic_image : file attache pic_user_id : 1 pic_name : abcd.jpg }
where file attached is the image i want to upload from the image view, How to achieve this?
this my function to upload image that is inside a dictionary
-(void)uploadImageWithparams:(NSDictionary *)params withDelegate:(id)delegateObject withHandler:(HMResponseBlock)block{
// This isn't actually my url btw
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@,%@",kBaseUrl,@"page=user"]]];
[request setHTTPMethod:@"POST"];
NSMutableArray *parameters = [[NSMutableArray alloc] init];
for (NSString *key in params.allKeys) {
if([key rangeOfString:@"pic_image"].location != NSNotFound){
[parameters addObject:@{@"fileName": key, @"value": params[key]}];
}else {
[parameters addObject:@{@"name": key, @"value": params[key]}];
}
}
NSLog(@"The parameters are %@",parameters);
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
if (param[@"fileName"]) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"%@\"\r\n", @"abcd"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:param[@"value"]];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}else {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", param[@"value"]] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSDictionary *json = nil;
NSError *err;
if(data){
json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&err];
}
block(json,err);
}
}];
[dataTask resume];
}