Submitting .txt file to web service - ios

HELP please..
I'm trying to upload .txt file to web service.. any idea please?
here how i used to send data to web service
self.responseData=[[NSMutableData alloc]initWithLength:0];
NSString *tempString=[[NSString alloc]initWithFormat:#"%#",Register_URL];
NSURL *url = [NSURL URLWithString:[tempString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
(void)[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

Just found solution .. hope it will help any one :)
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:yourFileName.txt];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath: fullFilePath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"yourServiceURL"]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"yourFileName.txt\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(),^ {
[self LogResult:returnString];
});
});
somewhere in your class implement "LogResult:" method .

Related

SQLITE database Uploading

Is there any way to upload , download to a server read the .sqlite file present in document directory from your iPhone application and use it as your database.
I tried by converting to binary data and uploading but the file is getting encrypted I cannot read or write it after restoring/downloading it from server.
Any suggestion?
Uploading task fetching the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *chatDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ChatDB.sqlite"];
NSString *contactDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ContactDB.sqlite"];
NSURL*ChatDB_url = [NSURL fileURLWithPath:chatDatabasePath];
NSURL*ContactDB_url = [NSURL fileURLWithPath:contactDatabasePath];
self.ChatDBData = [NSData dataWithContentsOfURL:ChatDB_url];
self.ContactDBData = [NSData dataWithContentsOfURL:ContactDB_url];
Uploading
-(void)UploadDbToServer:(NSData*)DB_Data ForDbName:(NSString*)dbName forExtension:(NSString*)extension andCallback:(void (^)(id))callback{
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%#chat-backup-upload",baseUrl]];
urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"7MA4YWxkTrZu0gW";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add DB data
if (DB_Data) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"DB\"; filename=\"%#.%#\"\r\n",dbName,extension] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: file/sqlite\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:DB_Data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSURLSessionConfiguration *sessionConf = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConf];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id jsonResponse= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
callback ((id) jsonResponse);
}];
[task resume];}
Downloading
(void)startDownload:(NSURL*)url {
NSURL *Url= [NSURL URLWithString:[NSString stringWithFormat:#"%#",url]];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue setMaxConcurrentOperationCount:5];
self.activeUrlString=[NSString stringWithFormat:#"%#",Url];
if (!self.session) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:#"image"];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:queue];
}
NSURLRequest* request = [NSURLRequest requestWithURL:Url];
self.task = [self.session downloadTaskWithRequest:request];
[self.task resume];}
Writing the downloaded file
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
//saving the files
NSData *DBData = [NSData dataWithContentsOfURL:location];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *chatDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ChatDB.sqlite"];
NSString *contactDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ContactDB.sqlite"];
if ([self.activeDownload isEqualToString:#"chat"]){
[DBData writeToFile:chatDatabasePath atomically:YES];
self.activeDownload = #"contact";
[self startDownload:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",pingovaURL,self.ContactDB_URL]]];
}else{
[DBData writeToFile:contactDatabasePath atomically:YES]; }}

How to pass the image on json server and convert that image into string and pass it into URL?

I try to pass the image on json and store on it but it couldn't pass on that server. i have make code for that so how to pass that image on json and how to convert that image into string and store on json.
NSString *urlSTR = [NSString stringWithFormat:#"http://IOSAPI/registration.php?Profile_Picture&User_Name=%#&First_Name=%#&Last_Name=%#&Email_ID=%#&Password=%#",_textFieldUserName.text,_textFieldFirstName.text,_textFieldLastName.text,_textFieldEmail.text,_textFieldPassward.text];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlSTR] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];
NSURLResponse *responce;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responce error:nil];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"RESPONCE %#",dictionary);
NSLog(#"RESPONCE %#",[dictionary valueForKey:#"status"]);
NSString *str = [NSString stringWithFormat:#"%#", [dictionary valueForKey:#"status" ]];
UIImage *images=self.imageView2.image;
NSData *imageData =UIImageJPEGRepresentation(images, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"picture\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlSTR]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:string] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString*s11= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",s11);
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSData *data = UIImageJPEGRepresentation(images, 1.0);
NSString *StrCoverImageData = [data base64EncodedStringWithOptions:0];
use this string to send over server.

how to upload multiple images to server ios?

I am trying to upload Image From my IOS device to server. when upload single image file to server it is successfully uploaded to my server. i want to upload multiple image files to server how can i do this.
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"icon.png"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
NSString *filename = #"icon";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
Muliple images upload attempted code
-(void)uploadImageToServer:(NSArray*)arrUploadData withTreatmentDetails:(NSDictionary *)dictArguments url:(NSString*)url
{
// COnvert Image to NSData
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
for (int i=0; i<[arrUploadData count]; i++)
{
NSData *dataImage = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyData"];
NSString *filename = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyimagename"];
if (dataImage)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Hello, You can do it by using NSMutableArray
For Example :
NSMutableArray *arrayImageData = [[NSMutableArray alloc]init];
Take images from imagepicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *filePath,*path;
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
[arrayImageData addObject:dataImage];
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"screenShot1.png"];
[picker dismissViewControllerAnimated:YES completion:nil];
}
At the time of posting image on Server use following code
for (int i = 0; i < [arrayImageData count]; i++)
{
[request setPostValue:[[MYUtility getInstance] base64StringFromNSData:[arrayImageData objectAtIndex:i]] forKey:[NSString stringWithFormat:#"Image%d", i + 1]];
}
Hope this will help for you...I used this code for saving multiple images on server.

Image not posting by base64 string on json

I am Posting a image on Server By json Post Webservice.I have to upload the image on base 64 .I am encoding my image to base 64 string but the Image is not posting on the server and not other things.There is No problem with the webservice.The image is uploading successfully in android.
selectedImage=[[NSData alloc]initWithData:UIImageJPEGRepresentation(image, 1.0)];
[[NSUserDefaults standardUserDefaults]setObject:selectedImage forKey:#"image"];
[[NSUserDefaults standardUserDefaults]synchronize];
strImage=[[NSString alloc]init];
strImage = [selectedImage base64Encoding];
strImage=[strImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strImage %#",strImage);
/*
NSData *b64DecData = [Base64 decode:strImage];
NSLog(#"strImage %#",strImage);
[bttnimage setBackgroundImage:[UIImage imageWithData:b64DecData] forState:UIControlStateNormal];
*/
NSString *post=[[NSString alloc]initWithFormat:#"name=%#&aboutMe=%#&chatId=%#&gender=%#&lookingFor=%#&city=%#&birthdate=%#&anniversarydate=%#&number1=%#&number2=%#&number3=%#&image=%#",[txtProfileName.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtComment.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[appDelegate.chatid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[bttnGender.titleLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[bttnLookingfor.titleLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtPlace.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[dobLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[anniversaeyLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNumber.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNum1.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNum2.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],strImage];
NSLog(#"post %#",post);
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *latrequest = [[NSMutableURLRequest alloc] init];
NSString *url=[NSString stringWithFormat:#"http://www.xyzAbc.org/iphone/updateProfile.php?%#",post];
NSLog(#"url %#",url);
[latrequest setURL:[NSURL URLWithString:url]];
Connection=[NSURLConnection connectionWithRequest:latrequest delegate:self];
[latrequest setHTTPMethod:#"POST"];
[latrequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[latrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[latrequest setHTTPBody:postData];
[latrequest release];
NSLog(#"latre %#",latrequest);
the code is above Please Let me know if I am missing something. Please any one Help me with that.
First add Base64.h and Base64.m files to your project. The following method will return Base-64 string from UIImage.
-(NSString*)getBase64StringfromImage:(UIImage*)image{
NSData *imageData = UIImageJPEGRepresentation(image,90);
NSString *ImgStr=[Base64 encode:imageData];
ImgStr=[ImgStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
return ImgStr;
}
Image posting is different in iOS when we compare it with Android.
And in iOS do this formate
NSString *urlString = [NSString stringWithFormat:#"********************/web-services/register_user.php?firstname=%#&lastname=%#&email=%#&password=%#&location=india&device=IPHONE",details.fname,details.lname,details.emailAddress,details.password];
// urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
UIImage *image=details.pic;
NSData *imageData =UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:string] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString*s11= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *responseDictionary1;
responseDictionary1 = [XMLReader dictionaryForXMLString:s11 error:nil];
////////
This will fix issue
Regards
Charan Giri

Form Data Request using NSURLConnection in iOS

I want to make http form post using NSURLConnection in iOS. I have two form fields and one file upload option in an HTML form. When I am doing same thing using NSURLConnection I am not getting a response.
NSString *urlString = #"http://url/test.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:filedata];
[body appendData:[[NSString stringWithFormat:#"&s=YL4e6ouKirNDgCk0xV2HKixt&hw=141246514ytdjadh"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"RETURNED:%#",returnString);
But when I use ASIHTTPRequest and write the following code it's working and I am getting a response.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://url/test.php"]];
[request setPostValue:#"YL4e6ouKirNDgCk0xV2HKixt&hw" forKey:#"ssf"];
[request setPostValue:#"141246514ytdjadh" forKey:#"sds"];
[request setData:filedata withFileName:#"myphoto.png" andContentType:#"image/jpeg" forKey:#"file"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"response:%#",response);
}
Can anyone tell me what I'm doing wrong with the NSURLConnection part?
You are not copying the example of that link. In that tutorial, the HTTPBody parameter is supposed to be an instance of NSData, not NSString.
[request setHTTPMethod:#"POST"];
NSString *myString = [NSString stringWithFormat:#"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];
I tried this code for uploading the image and its working. Added boundry.
NSString *urlString = #"URL";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"Test.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
This is working fine for me.
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *req=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http:///URL/iinsert.php"]];
NSString *myreqstr=#"name=abhii&address=knrr";
NSData *myreqdata=[NSData dataWithBytes:[myreqstr UTF8String] length:[myreqstr length]];
[req setHTTPMethod:#"POST"];
[ req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[ req setHTTPBody: myreqdata ];
//[req setValue:#"abhii" forHTTPHeaderField:#"name"];
//[req setValue:#"kar" forHTTPHeaderField:#"address"];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSLog(#"%#",data);
NSString *returnstring=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",returnstring);
// Do any additional setup after loading the view, typically from a nib.
}
Try this ....
NSURL *url = [NSURL URLWithString:#"URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *myRequestString =#"Request string";
NSLog(#"%#",myRequestString);
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
[ request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You have several
rn
in the end of your strings. All of them should be
\r\n
More precisely it should be:
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

Resources