Does UIAlert need some sort of delay? - iphone

Trying to alert user when internet is unavailable (and retry when they dismiss message). The screen slightly dims (in preparation for alert), but the alert never displays.
Is the while loop interfering with the alert?
-(NSArray*)getResponse:(NSString*)page {
NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;
NSString *legalAddressURL;
NSArray *separatedData;
legalAddressURL = [NSString stringWithFormat:#"%#%#", SERVER,
[page stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: legalAddressURL]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
while ([error code]){
if (isNetAvailable){
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Internet Connection"
message:#"Server is down" delegate:self cancelButtonTitle:#"Try again"
otherButtonTitles:nil] autorelease];
[alert show];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
} else {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Internet Connection"
message:#"No access to net" delegate:self cancelButtonTitle:#"Try again"
otherButtonTitles:nil] autorelease];
[alert show];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
}
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
separatedData = [stringReply componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#","]];
return separatedData;
}

After showing the alert using [alert show], you should exit the getResponse method, because the internal message loop should continue.
You can't simply continue looping and showing alerts.
I could be wrong, but I'm pretty sure that's the reason.

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

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"

Connect iphone app to mysql data base

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);

How to twit a picture with some text in iPhone

I want to know that is there any way I can post picture in twitter with some text, some one has suggested to use "http://tinyurl.com/".I don't know where to start, in my previous application I twit successfully but that only contains text.
A proper direction to proceed would be a great help.
There are a couple of ways. I would suggest you use ShareKit. It does most of the work for you.
To post image to twitter we have to first post the image to twit pick and then we have to send that url to twitter that is the process to send image to twitter this is the sample code to send image to twitter..........
NSString *postUrl = #"https://api.twitter.com/1/statuses/update.json";
ASIFormDataRequest *request = [[ASIFormDataRequest alloc]
initWithURL:[NSURL URLWithString:postUrl]];
NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:statusText.text
forKey:#"status"];
NSLog(#"%#",postInfo);
NSString *str1= statusText.text;
NSLog(#"Status posted. HTTP result code: %d", request.responseStatusCode);
[request release];
[statusText resignFirstResponder];
ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"]];
[req addRequestHeader:#"X-Auth-Service-Provider" value:#"https://api.twitter.com/1/account/verify_credentials.json"];
[req addRequestHeader:#"X-Verify-Credentials-Authorization"
value:[oAuth oAuthHeaderForMethod:#"GET"
andUrl:#"https://api.twitter.com/1/account/verify_credentials.json"
andParams:nil]];
[req setData:UIImageJPEGRepresentation(imageView.image, 0.8) forKey:#"media"];
// Define this somewhere or replace with your own key inline right here.
[req setPostValue:#"74734e805f2ad85afae441ca12c16087" forKey:#"key"];
[req startSynchronous];
NSLog(#"Got HTTP status code from TwitPic: %d", [req responseStatusCode]);
NSLog(#"Response string: %#", [req responseString]);
NSDictionary *twitpicResponse = [[req responseString] JSONValue];
NSLog(#"%#",[[req responseString] JSONValue]);
textView.text = [NSString stringWithFormat:#"Posted image URL: %#", [twitpicResponse valueForKey:#"url"]];
NSString *str=[NSString stringWithFormat:#" %#",[twitpicResponse valueForKey:#"url"]];
NSLog(#"%#",str);
if([str isEqualToString:#" (null)"])
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"Could not authenticate you(header rejected by twitter)" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *postUrl = #"https://api.twitter.com/1/statuses/update.json";
ASIFormDataRequest *request = [[ASIFormDataRequest alloc]
initWithURL:[NSURL URLWithString:postUrl]];
NSString *txtmessage=[str1 stringByAppendingString:str];
/*NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:[twitpicResponse valueForKey:#"url"]
forKey:#"status"];*/
NSMutableDictionary *postInfo = [NSMutableDictionary
dictionaryWithObject:txtmessage
forKey:#"status"];
for (NSString *key in [postInfo allKeys]) {
[request setPostValue:[postInfo objectForKey:key] forKey:key];
}
[request addRequestHeader:#"Authorization"
value:[oAuth oAuthHeaderForMethod:#"POST"
andUrl:postUrl
andParams:postInfo]];
[request startSynchronous];
if(request.responseStatusCode!=200)
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"Already posted" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:#"sucess" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
NSLog(#"Status posted. HTTP result code: %d", request.responseStatusCode);
statusText.text = #"";
[request release];
[statusText resignFirstResponder];
}