I am trying to upload an image along with some text. I am able to POST the text but somehow the image doesn't reach to server.
Following is my code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *password = [[Utilities sharedConfiguration] sha1:txtPassword.text];
NSString *post = [NSString stringWithFormat:#"id_sender=%#&token=%#&array_receiver=%#&message=%#&time_allowed=%#&password=%#",[defaults objectForKey:#"id_user"],[defaults objectForKey:#"token"],selectedContact,txtMessage.text,txtTime.text,password];
NSLog(#"post %#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableData *data = [NSMutableData dataWithData:postData];
//NSMutableData *data = nil;
if(myimage!=nil){
NSString *boundary = #"---------------------------14737809831466499882746641449";
[data appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/png\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:#"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[NSData dataWithData:UIImagePNGRepresentation(myimage)]];
}
NSString *postLength = [NSString stringWithFormat:#"%d", [data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://www.myurl.com/send_message_17294.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
[MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
[NSURLConnection connectionWithRequest:request delegate:self];
You can use AFNetworking so you don't have to digg into the multi-part request format.
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://hostport"]];
NSDictionary *simpleParams = #{ #"key": #"value" };
NSMutableURLRequest* request = [client multipartFormRequestWithMethod:#"POST" path:#"/path" parameters: simpleParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:fileData
name:#"paramName"
fileName:#"filename.png"
mimeType:#"image/png"];
}];
Then create an operation depending on the expected response. For example if you expect JSON:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// handle success
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// handle error
}];
You can get more information in the AFNetworking documentation.
Try this : Its a Synchronous Request. And image is in base64 string format
NSString * param = [NSString stringWithFormat:#"%#=%#&%#=%#&%#=%#",
#"uphoto",imageData, #"category",categoryName, #"name",FIRSTNAME]; // parameters
NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://www. ..."];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *res = nil;
NSData *responceData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
if (error)
{
//handle error
return nil;
}
else
{
}
Related
I am trying to post data to WCF service from iPhone Application but somehow service doesn't seems to be call through the iPhone. I received a Status Code = 999.
NSString *urlString = #"http://192.168.1.192/MSservice/SecureRegistration";
NSURL *URL = [NSURL URLWithString:
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *postData = [bodyData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"Error %#", errorReturned.localizedDescription);
}
else
{
NSLog(#"Data %#", data);
NSString *responseString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response %#", responseString);
}
Request data
NSDictionary *tmp = #{#"name":#"Kousik",#"age":#"24",#"location":#"bangalore"};
NSString *postdata = [NSString stringWithFormat:#"request = %#",tmp];
//now postdata is
//request = {
"age" = "24";
"location" = "bangalore";
"name" = "Kousik";
}
but I want this NSDictionary should be inside a string so that in server I can eval it and get the dictionary back.
Here I want something like toString() is java or str() in pyhton.
This is my Http request:-
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *preparedPostData = [postdata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postdata length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:preparedPostData ];
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse response,NSData data,NSError *error){
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if(complect)
complect(result,error);
}
];
Update
My request is going to server properly but The problem is with data structure.
when I am trying to access the data with request key then it is giving error because the value for the request key is not supported in server as this value is having = sign in between. So what I want is that to make the requset data structure properly.want to send the NSDictionary itself as a string.
postdata should be something like this
request = "{
age : 24;
location : bangalore;
name : Kousik;
}"
I dont want to use application/json.
NSString *stringURL = [NSString stringWithFormat:#"name=%#&age=%#&location=%#",#"Kousik",#"24",#"bangalore"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,API_SaveContctListToAddressBook]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[stringURL dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
data = [[NSData alloc] init];
}
NSDictionary *dic =[ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
completionHandler(dic, NO);
}];
Use NSJSONSerialization to convert your dictionary to NSData and then attach it on HTTPBody
NSData *httpBody = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,APIPath]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:httpBody];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//Handling code
}];
I have one text field I need to send two data's to API.
NSString *post =[NSString stringWithFormat:#"val1=%#,val2=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"val1"],val2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://api.test.com/send"]];
[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;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"log%#",str);
}
I need to send only raw data to API this is my code.Please check and let me know thanks
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
//error
}
else
{
//no error
}
Try this
Have you tried converting it to NSData and sending that?
Here's the conversion:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
That will give you the data in bytes, then just pass it in with the normal networking function calls.
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
}];
}];
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];
}