Connect iphone app to mysql data base - iphone

I have app i want to connect to iphone app i have done code and also php code problem is that i am always getting Incorrect password alert view . I aam entering correct user name and password but again it displays error alert view
NSString *post =[NSString stringWithFormat:#"UserName=%#&UserPassword=%#",userNameTextField.text, userPasswordTextFiled.text];
NSString *hostStr = #"http://www.myurl.com/emrapp/connect.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
if([serverOutput isEqualToString:#"Yes"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Congrats" message:#"You are authorized "
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
} else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Username or Password Incorrect"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
And my server side code is
<?php
$con = mysql_connect("emriphone.db.6420177.hostedresource.com","emriphone","Light12-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("emriphone", $con);
$u=$_GET['UserName'];
$pw=$_GET['UserPassword'];
$query = sprintf("SELECT UserName,UserPassword from appUsers WHERE UserName='%s' AND UserPassword='%s'", mysql_real_escape_string($u),mysql_real_escape_string($pw));
$login=mysql_query($query,$con) or die(mysql_error());
if(mysql_num_rows($login)==1){
$row =mysql_fetch_assoc($login);
echo 'YES'; exit;
}
else{
echo'NO';exit;
}
mysql_connect($con);
?>

Try Using Following Code
NSString *data = [[NSString stringWithFormat:#"UserName=%#&UserPassword=%#",userNameTextField.text, userPasswordTextFiled.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// preaparing URL request to send data.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"http://www.myurl.com/emrapp/connect.php?"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];
NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response:is %#",str);

Related

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"];

using HTTP Post method how to make login page in iphone

I'm have created a Login view. Everytime I login it gives me login Success message will be displayed. even if I enter wrong username and password.I am created login page static.The menctioned link is sample web services link. This is the method I'm using right now:Please give me any idea.Thanks in advance.
loginPage.m
-
(IBAction)login:(id)sender
{
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"HTTP://URL"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
NSLog(#"connection successful");
}
else
{
NSLog(#"Failed");
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
// NSURL *theURL=[response URL];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if(receivedData)
{
NSLog(#"success",[receivedData length]);
}
else
{
NSLog(#"Success",[receivedData length]);
}
}
NSString *string= [NSString stringWithFormat:#"your Url.php?&Username=%#&Password=%#",username,password];
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!!!
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtUserName text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Пожалуйста заполните все поля!!!" :#"Авторизация не удолась!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[txtUserName text],[txtPassword text]];
NSURL *url=[NSURL URLWithString:#"http:xxxxxxxx.xxx/?"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding 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];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
if([jsonObject objectForKey:#"error"])
{
[self alertStatus:#"" :#""];
} else {
[self alertStatus:#"" :#""];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
}
Try below code.
-(void)webservice_Call
{
NSString *urlString=#"http://api.openweathermap.org/data/2.1/find/city?lat=10.369&lon=122.5896";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSDictionary *resDictionary = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:Nil];
}
Post Method for iOS 9 Version
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
   
[post setValue:#“25” forKey:#"user_id"];
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://your/url]]];
      
[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];
      
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
 
// Create a data task object to perform the data downloading.
    
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 
    data = [[NSData alloc]initWithData:urlData];
    NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}];
      
[task resume];
-(void)apiCode
{
NSString *string= [NSString stringWithFormat:#"http:url...project_id=1&user_id=58&question=%#&send_enquiry=%#",self.txtTitle.text,self.txtQuestion.text];
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 = #"success";
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];
}
}

how to get server response and if server response is "Success" after show alert by JSON using objective c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
NSString *data = [NSString stringWithFormat:#"username=%#&password=%#",usertxt.text,pwdtxt.text,[NSNumber numberWithBool:YES]];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// preaparing URL request to send data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString *url = [NSString stringWithFormat:URL_PATH];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];
NSURLResponse *_response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//Print Server Response
NSLog(#"Login response:%#",str);
//Parse JSON string into an NSDictionary
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData
options:kNilOptions
error:&error];
Try This
Don't need to use JSON simply try this code to get response from server
NSString *string= [[NSString alloc]initWithFormat:#"url"];
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];
}
if your response string is success than put this in the place of #"1"

Uploading image to server with base64 haxcode with userid parameter in iPhone

I'm using this code but problem is that it encodes the Haxcode in nsdata conversion block I want to send same has code which I'm getting with userid which is fixed integer. Please help.
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image1, 0)];
//image.image=image1;
[Base64 initialize];
NSString *b64EncStr = [Base64 encode:imageData];
NSLog(#"encoded.%#",b64EncStr);
NSURL *url = [[NSURL alloc] initWithString:updateimageURL];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
[req setHTTPMethod:#"POST"];
NSString *trimmed = [b64EncStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
paramDataString = [NSString stringWithFormat:#"Id=%d&FromString=%#",100,trimmed];
NSLog(#"%#",paramDataString);
NSData* aData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPBody: aData];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if (theConnection)
{
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData=data;
[data release];
}
else {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:#"Check your networking configuration." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
[url release];
[req release];
It is making the URL connection in right way but response is server error.
First Convert UImage to NSData and from NSData to base64string and then pass that to your Webservice
finalImagePath = [imageData base64EncodedString];
NSString *strImageData = [finalImagePath stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
and then send strImageData to your webserivce.
While retriving from server use
NSString *strImageData = [finalImagePath stringByReplacingOccurrencesOfString:#"%2B" withString:#"+"];
Upload base64 string directly to your server
paramDataString = [NSString stringWithFormat:#"Id=%d&FromString=%#",100,b64EncStr];

Capturing PHP Response Through NSJSONSerialization

Hi I have this code here.
NSString *name = [[NSString alloc] initWithFormat:[nameField text]];
NSString *street = [[NSString alloc] initWithFormat:[streetField text]];
NSString *city = [[NSString alloc] initWithFormat:[cityField text]];
NSString *state = [[NSString alloc] initWithFormat:[stateField text]];
NSString *zip = [[NSString alloc] initWithFormat:[zipField text]];
NSString *urlToAuthPage = [[NSString alloc] initWithFormat:#"&name=%#&street=%#&city=%#&state=%#&zip=%#&lat=%#&lon=%#", name, street, city, state, zip, str1, str2];
NSData *postData = [urlToAuthPage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d",[urlToAuthPage length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://yourlink.com/poop.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSError *error;
NSMutableArray *infoArray = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:&error];
NSLog(#"%#", [infoArray objectAtIndex:0]);
if (conn) {
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your party has been successfully posted" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[successAlert show];
//NSLog(conn);
nameField.text = #"";
streetField.text = #"";
cityField.text = #"";
stateField.text = #"";
zipField.text = #"";
[nameField resignFirstResponder];
[streetField resignFirstResponder];
[cityField resignFirstResponder];
[stateField resignFirstResponder];
[zipField resignFirstResponder];
}
What I'm trying to do is get the response the server gives out that is in NSJon. I'm trying capture what is below. I've tried using an NSMutableArray to get it but it didn't work. What am I doing wrong?
{"status":1}
The problem is that NSJSONSerialization answers witha NSDictionary, not an NSMutableArray. You can't force it to be an array, since it needs a value and a key (in this case the key is "status" and the value is "1")