Posting to the webserver the data in iPhone - iphone

I searched but I can't solve my problem .Here i want post the data to server. I have one user default, textview and textfield. please help out from this.
NSUserDefaults *getting= [NSUserDefaults standardUserDefaults] ;
userID1=[getting objectForKey:#"uId"];
NSString *bodyString=[NSString stringWithFormat:#"userId=%#&question=%#&categoryId=%#",userID1,askTextViewObj.text,specialistField.text];
[bodyString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",bodyString);
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"XXXXXXXXXXXXXXXXXX" ] cachePolicy:0 timeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request addValue:[NSString stringWithFormat:#"%d", [bodyString length]] forHTTPHeaderField:#"content-Length"];
connection=[NSURLConnection connectionWithRequest:request delegate:self ];
if (!connection)
{
UIAlertView* aler = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"Failed to Connect Server " delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[aler show];
}
else
{
NSLog(#"Connection is Successfully");
}

Related

How to post data through json in iOS

I have attempted to post data into server through json. Suppose i have just one field named username into my xib. Now i am posting this data into server. I have written this code
NSString *uname=txt_name.text;
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://mypath/index.php?params=123"]];
[request setHTTPMethod:#"POST"];
// NSString *postString = #"Email=me#test.com";
[request setValue:[NSString
stringWithFormat:#"%d", [uname length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[uname
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
NSLog(#"text",uname);
But i do not know the data is posting or not. I want to post my input data into console of in Xcode but there nothing is showing. What the reason..? Whats wrong is going on..?
You need the following request:
NSDictionary *dataDict = #{#"uname": <YOUR_UNAME>};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://mypath/index.php?params=123"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:#"%d",postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
To ensure the server have got your data use
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = httpResponse.statusCode;
...........
}
In case of success you will get statusCode = 200.
NSString *string= [NSString stringWithFormat:#"your Url.php?&Username=%#",username];
NSLog(#"%#",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData: %#", str);
NSString *str1 = #"1";
if ([str isEqualToString:str1 ])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Successfully" message:#"" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Try Again" message:#"" delegate:self cancelButtonTitle:#"Try Later" otherButtonTitles:#"Call", nil];
alert.tag = 1;
[alert show];
}
Don't need to use JSON you can do this without JSON in a esay way!!!

How can I create a Login Page in Xcode?

So I'm working on creating a login page. But I'm not sure what part I'm missing here! Every time I try to login it says the credentials are invalid.... I'm betting I got confused with POST and GET methods.
Any help would be appreciated! Thanks.
My Code is below:
- (IBAction)login:(id)sender {
if ([userName.text isEqualToString:#""] || [password.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Please fill in all the fields!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
NSURL *url = [NSURL URLWithString:#"http://WEBSITEHERE/api/users/AuthenticateUser"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *params = #{#"userName": userName.text, #"password": password.text};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSLog(#"PARAMS = %#", params);
[request setHTTPMethod:#"GET"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSData *dataURL = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSString *responseString = [[NSString alloc]initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
if ([result isEqualToString:#"1"])
{
UIStoryboard *mainStoryboard=[UIStoryboard
storyboardWithName:#"MainStoryboard" bundle:nil];
Home *mainView=[mainStoryboard
instantiateViewControllerWithIdentifier:#"mainView"];
mainView.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
[self presentViewController:mainView animated:YES completion:nil];
}else
{
// invalid information
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"You must have entered something wrong! Try again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
I'm not sure how your server is setup but this is how I setup a request for authentication in one of my recent apps:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", kBaseServerURL, sAuthMethod]]];
[request setHTTPMethod:#"GET"];
[request setValue:_username forHTTPHeaderField:#"j_username"];
[request setValue:_password forHTTPHeaderField:#"j_password"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

NSURLConnection error not working

I am trying to detect if there is an error in my request using the if statement on theConnection. It enters the first part if successful fine but does not enter the else if there is an error. I am not sure why.
- (void)vehicleSearchRequest:(NSData *)postBodyData
{
NSString *address = [NSString stringWithFormat:#"http://%#", serverAddress];
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithFormat:#"%#", address];
NSURL *url = [NSURL URLWithString:databaseURL];
NSString *postLength = [NSString stringWithFormat:#"%d", [postBodyData length]];
//SynchronousRequest to grab the data, also setting up the cachePolicy
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //if request dose not finish happen within 60 second timeout.
// Set up request
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/octet-stream" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:postBodyData];
[request setTimeoutInterval:180];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
// do animation thankyou here
NSLog(#"Sucsess!");
[self submitSuccessful];
} else {
// Inform the user that the connection failed from the connection:didFailWithError method
NSLog(#"Connectin ERROR!!!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection error, Please try again" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Your code checks to see whether it was able to instantiate an NSURLConnection or not. This is a useful safety check, but will only fail in practice if you pass it a URL that the system does not support.
The connection itself is asynchronous, and so will take a little while to tell you if there was a problem or not. Implement its delegate methods to hear back from the server.

ASIHTTPRequest login page

I try to make an iphone application that can login to the web application that use the https securing the user information.Now i am stuck in the login page. I don't know how to check the real account in the website of user when logging in by my application. I got the response only 200 even if i put the wrong account.
here is my code:
- (IBAction)clickOK:(id)sender {
NSURL *url = [NSURL URLWithString:#"https://www.freelancer.com/users/login.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request setDelegate:self];
request.shouldPresentCredentialsBeforeChallenge = YES;
[request setRequestMethod:#"POST"];
[request setPostValue:usernameField.text forKey:#"username"];
[request setPostValue:passwordField.text forKey:#"passwd"];
request.timeOutSeconds = 30;
[request setDidFailSelector:#selector(requestLoginFailed:)];
[request setDidFinishSelector:#selector(requestLoginFinished:)];
[request startAsynchronous];
}
- (void)requestLoginFailed:(ASIHTTPRequest *)request
{
//notify user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error sending request to the server" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
- (void)requestLoginFinished:(ASIHTTPRequest *)request
{
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
NSLog(#"StatusCode: %d", statusCode);
NSLog(#"StatusMessage: %#", statusMessage);
}
Can anyone suggest me how to check the real account of this website and keep user login?
Thanks for any help
You've started something Asynchronously
[request startAsynchronous];
And then just expected it to return something straight away:
NSLog(#"%#",[request responseString]);
NSLog(#"%d",[request responseStatusCode]);
You need to put something like this:
[request setDidFinishSelector:#selector(didFinishRequest:)];
And then move your NSLogs and any other stuff that leeches off of the response into that method.

passing parameter to the web service working code

again i am trying with soap method, but this time i downloaded the charles and observe the request that i create from my code. Chales showing "failed to parse data(org.xml.sax.saxparser exception:content is not allowed in prolog)"
here is my code:
NSString *soapMsg = [[NSString alloc] initWithFormat:#"\n"
"\n"
""
"\n"
"%#\n"
"%#\n"
"%#\n"
"%#\n"
"\n"
"\n"
"\n",str1,str2,str3,str4];
NSLog(soapMsg);
NSURL *url = [NSURL URLWithString:#"http://192.168.0.218:84/WebServiceCustomerByAmit/Service.asmx?op=InsertCustomerInformation"];
NSLog(#"url. . . .%#", url);
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSLog(#"req....%#", req);
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
NSLog(#"msgLength. . .%#", msgLength);
[req addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue: #"http://tempuri.org/InsertCustomerInformation" forHTTPHeaderField:#"SOAPAction"];
[req addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"req....%#", req);
NSError *error;
NSURLResponse *response;
//NSData *urlData=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if( theConnection )
{
//webData = [[NSMutableData data] retain];
NSLog(#"theConnection is OK");
}
else
{
NSLog(#"theConnection is NULL");
}
if(!response){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Error" message:#"Failed to Connect to the Internet" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Connection Successful" message:#"Connected to the Internet" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert1 show];
[alert1 release];
}
}
help!! thanks in advance!!
You are asking how to include ASIHTTPRequest in your project, right? Copy and paste ASIHTTPRequest's folder in your project's folder and add this in your code:
#import "ASIHTTPRequest.h"
Note that ASIHTTPRequest is an external library and not part of the iOS SDK.