Post Two images to Web server - ios

Below code i wrote for sending two images. But i failed to find the code why its not working. i am new to iOS and even stackoverflow. Still am thinking the code is ok. just help me to find my mistake. how i modify the code to able to send two images with different services(each service have a separate url).
NSString *requestString =[NSString stringWithFormat:#"requestUserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#&AgeRange=%#",userID,CategoryId1,continentTextfield.text,countrytextfield.text,citytextfield.text,GenderText.text,imagename,ageTextfield.text];
NSLog(#"request%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
if ([response statusCode]==200)
{
self.userId=[[NSUserDefaults standardUserDefaults]objectForKey:#"Sendd"];
NSLog(#"recievedData%#",receivedData);
NSString *requestString1 =[NSString stringWithFormat:#"requestUserId=%#&ImageId=%#&=ImageName%#",userID,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url1=[NSString stringWithFormat:#" http://37.187.152.236/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init] ;
[request1 setURL:[NSURL URLWithString:url1]];
[request1 setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request1 setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request1 addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[NSData dataWithData:data]];
[request setHTTPBody:body1];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
homeViewController *homVew =[[homeViewController alloc]initWithNibName:#"homeViewController" bundle:nil];
self.navigationItem.hidesBackButton = YES;
[self.navigationController pushViewController:homVew animated:YES];
}

Related

Create and send JSON data to server using Objective C

I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)MessagePost{
NSString * post =[NSString stringWithFormat:#"http://url.com/clients/project_id=%#&user_id=58&question=%#&send_enquiry=Send",[[self.recordchat objectForKey:#"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(#"String : %#",returnstring);
if (postdata){
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:#"status"];
NSLog(#"Status dict = %#",latestLoans);
} else{ NSLog(#"Error while posting messages.");}}
instead of writing NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"Username"];
[post setValue:self.passwordField.text forKey:#"Password"];
Try this -
- (IBAction)loginAction:(UIButton *)sender
{
NSDictionary *dictDetails = #{
#"Username" : self.userNameField.text,
#"Password" : self.passwordField.text
};
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required..
Thank you all for your time and support..
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"username"];
[post setValue:self.passwordField.text forKey:#"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(#"JSON Summary: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response Error= %#", response);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Random Output= %#", jsonObject);
[self performSegueWithIdentifier:#"DASHBOARDSEGUE" sender:sender];
}else {
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}

How to send an object as a parameter for a POST request in iOS?

I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"APPLICATION/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"APPLICATION/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method

NSURLSession for sending multiple images by multiple urls

The below code i am using for sending multiple images along with the text. but only one image is saving in Web server. Here the problem is i need to get response from the first url and i've to assign it to the second url.
NSLog(#"PassedID%#",PassedUserId);
NSLog(#"integer=%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"Person"]);
NSString *CategoryId=#"3";
NSString *imagename=#"ComparisonObject";
NSString *requestString =[NSString stringWithFormat:#"UserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#",PassedUserId,CategoryId,continentTextfield.text,countrytextfield.text,citytextfield.text,GenderText.text,imagename];
NSLog(#"%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *uploadImage1 = [session dataTaskWithRequest:request completionHandler:^(NSData *data2, NSURLResponse *response, NSError *error) {
// Finish uploading image 1
// Get response and data to prepare to update image 2
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage1, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"recievedData%#",receivedData);
NSString *imagename=#"ComparisonObject";
NSString *requestString1 =[NSString stringWithFormat:#"UserId=%#&ImageId=%#&=ImageName%#",PassedUserId,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSURLSessionDataTask *uploadImage2 = [session dataTaskWithRequest:request2 completionHandler:^(NSData *data1, NSURLResponse *response, NSError *error) {
NSLog(#"recievedData%#",receivedData);
NSString *imagename=#"ComparisonObject";
NSString *requestString1 =[NSString stringWithFormat:#"UserId=%#&ImageId=%#&=ImageName%#",PassedUserId,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage2, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
// Finish uploading image 2
}];
}];

Post multiple images into web server

The code make me very happy to Post image into Web server. its working smart for single image. The code what i've to used to Post a single image is
NSLog(#"%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertFacialImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
Then i failed to jump over the hurdle, Failed to Post 2 images with different services.The truth behind my failure is after uploading of the 1st image, server generate response then i've attach the response to second service. i did it properly but failed because i made the connection run 2 times for 2 images.but Web services team asking me that run it in a single connection.The code which i is used, which i need to modify is
Posting 1st image
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage1, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %ld", (long)[response statusCode]);
Generating Response
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"%#" , error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *e;
jsonDict1 = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingMutableContainers error: &e];
compareId = [jsonDict1 valueForKey:#"ImageId"];
NSLog(#"JSONN%#" , jsonDict1);
compareId = [results.firstObject objectForKey:#"ImageId"];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.compareId forKey:#"Sendy"];
[defaults synchronize];
NSLog(#"compareId:%#",compareId);
results = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:&e];
}
}
after this step is response is generating good and i can pass it to the second string. so no problem with the server response.
*Post 2nd Image *
NSString *url1=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init] ;
[request1 setURL:[NSURL URLWithString:url1]];
[request1 setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request1 setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage2, 0.2f);
[request1 addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[NSData dataWithData:data]];
[request1 setHTTPBody:body1];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request1 delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSLog(#"Status code: %ld", (long)[response statusCode]);

Issue with large size images in HTTP Post

See my code which i used to post image in Web server. I can send small size image. but its not working for the large size images. Where i should modify this code to enable large size images
NSString *requestString =[NSString stringWithFormat:#"UserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#&AgeRange=%#",UserId,CategoryId,continentTextfield.text,countrytextfield.text,citytextfield.text,gender,imagename,ageTextfield.text];
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/InsertFacialImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImagePNGRepresentation(chosenImage);
// NSData *data = [NSData dataWithData:UIImagePNGRepresentation(chosenImage)];
[request addValue:#"image/png" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq)
{
NSLog(#"Connection Sucessful");
}
else {
NSLog(#"failed");
}
[connReq start];
CGFloat compr = 0.9f; //comress the size of the image
CGFloat maxCompre = 0.1f; //max allowed compression from 0 to 1
int maxSize = 250*1024; //max file size
NSData *imageData = UIImageJPEGRepresentation(yourImage, compr);
while ([imageData length] > maxSize && compr > maxCompre)
{
compr -= 0.1;
imageData = UIImageJPEGRepresentation(yourImage, compression); //compress the size
}
finally u pass the imageData to the server

Resources