Below is my code and I want to perform segue based on response string, but couldn't, can someone watch out my code and tell me what's wrong.
and when I am entering value in contact no. textfield,app is terminating with the error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <UITextField: 0x7faae2079980; frame = (20 353; 280 45); text = '9876543210'; clipsToBounds = YES; opaque = NO; autoresize = W+TM+BM; gestureRecognizers = <NSArray: 0x7faae2097250>; layer = <CALayer: 0x7faae2083bd0>>.'
Code I have try:
- (IBAction)Register:(id)sender {
if ((uname.text.length==0)&&(uemail.text.length==0)&&(ucontact.text.length==0)&&(upwd.text.length==0)&&(confirmpwd.text.length==0)){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Can not Register"
message:#"All the Fields are Mandatory"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alert show];
}
else{
NSString *emailString = uemail.text;// storing the entered email in a string.
//Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest=[NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
if(([emailTest evaluateWithObject:emailString]!=YES)||[emailString isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Enter your email in abc#example.com format." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
uemail.text = #"";
return;
}
}
NSString *mobile=ucontact.text;
NSString *numberRegEx = #"([0-9]{10})";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberRegEx];
if ([numberTest evaluateWithObject:ucontact] != YES||[mobile isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Enter a Valid Number." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
uemail.text = #"";
return;
}
if ((upwd.text)!=(confirmpwd.text)) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Password Do Not Match"
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alert show];}
NSURL *url = [NSURL URLWithString:#"http://108.179.246.128/connectme/service/registration.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSString *params=[NSString stringWithFormat:#"name=%#&email=%#&mobile=%#&passwrd=%#",self->uname.text,self->uemail.text,self->ucontact.text,self->upwd.text];
NSData *postData = [params dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:rq returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(#"Login response:%#",str); //getting response
// [self performSegueWithIdentifier:#"activity" sender:self];
if([str isEqual: #"Successfully Registered"])
{
[self performSegueWithIdentifier:#"login" sender:self];
}
else if([str isEqual:#"Sorry Email address already taken"])
{
UIAlertView *alertit=[[UIAlertView alloc] initWithTitle:#"Can not Register"
message:#"Email Address already Taken"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alertit show];
}
}
For your second question that is crashing, it is because you need to pass the textField.text not the UITextField object. So it should be mobile variable that contain text of textField instead of ucontact textField object.
[numberTest evaluateWithObject:mobile]
Related
I am using some text fields, and text field validations. I have shown below my code, In this code click button event and all text field text save on web server, In this code validation running only on empty text field. But i want to correct email address validation and all text field character length fixed.I tried to many times but some time condition wrong and some time don't show alert view and some time don't save text field text. How it possible please help, Thank you
My code
- (IBAction)submit:(id)sender {
if(self.txname == nil || [self.txname.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Name"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.txemail == nil || [self.txemail.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Email"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.tx_phone == nil || [self.tx_phone.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Phone"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.txcomment == nil || [self.txcomment.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Comment"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else
{
//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY URL"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"name=%#&email=%#&phone=%#& comment=%#&",_txname.text,_txemail.text,_tx_phone.text,_txcomment.text,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Success"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
[self.view endEditing:YES];
self.txname.text=#"";
self.txemail.text=#"";
self.tx_phone.text=#"";
self.txcomment.text=#"";
}
}
do like
- (IBAction)submit:(id)sender {
if (![txname hasText]) {
[self showAlertView:#"Alert" message:#"name is empty"];
}
else if (![txemail hasText])
{
[self showAlertView:#"Alert" message:#"email is empty"];
}
else if ([self isValidEmailAddress:txemail.text] == NO)
{
[self showAlertView:#"Alert" message:#"Invaildemail"];
}
else
{
// call webservice for succes
}
Create the alertcontroller
- (void)showAlertView:(NSString*)title message:(NSString*)message
{
UIAlertController* alertMessage = [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action){
}];
[alertMessage addAction:yesButton];
[self presentViewController:alertMessage animated:YES completion:nil];
}
for email validation
- (BOOL)isValidEmailAddress:(NSString *)emailAddress
{
//Create a regex string
NSString *stricterFilterString = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;
//Create predicate with format matching your regex string
NSPredicate *emailTest = [NSPredicatepredicateWithFormat:
#"SELF MATCHES %#", stricterFilterString];
//return true if email address is valid
return [emailTest evaluateWithObject:emailAddress];
}
updated
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.txname)
{
// Prevent crashing undo bug – see note below.
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 25;
}
return YES;
}
I did it in my code, Do like following Way:
- (IBAction)submit:(id)sender {
if (![self isFormValid]) {
return;
}
NSError *error;
if (!error)
{
UIAlertView *signupalert = [[UIAlertView alloc]initWithTitle:#"Congratulations" message:#"Record Added Successfully" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[signupalert show];
}
}
-(BOOL)isFormValid
{
NSString *emailRegEx =#"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest =[NSPredicate predicateWithFormat:#"SELF MATCHES %#",emailRegEx];
if (txname.text && txname.text.length==0)
{
[self showErrorMessage:#"Please enter name"];
return NO;
}
else if (tx_phone.text && tx_phone.text.length!=10)
{
[self showErrorMessage:#"Please enter valid phone number"];
return NO;
}
else if([emailTest evaluateWithObject: txemail.text]==NO)
{
[self showErrorMessage:#"Please enter Valid Email_id"];
return NO;
}
else if (txcomment.text && txcomment.text.length==0)
{
[self showErrorMessage:#"Please enter comment"];
return NO;
}
return YES;
}
-(void)showErrorMessage:(NSString *)message
{
UIAlertView *alertmessage = [[UIAlertView alloc]initWithTitle:#"Error" message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertmessage show];
}
-(BOOL) NSStringIsValidEmail:(NSString *)checkEmail
{
BOOL stricterFilter = NO;
NSString *filter = #"^[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *lstring = #"^.+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkEmail];
}
Hello for the life of me I cannot figure out why I am getting the following error during my signup process. Attached is the picture of what I'm getting this error when I enter a uppercase letter inside the username textfield.
Call Signup Fuction:
- (void)signUpCode {
NSString *str = #"09";
str = [_firstNameField.text isEqualToString:#""]?#"Please provide firstname":[_lastNameField.text isEqualToString:#""]?#"Please provide lastname":[_usernameField.text isEqualToString:#""]?#"Please provide username":[_emailField.text isEqualToString:#""]?#"Please provide email":[_passwordField.text isEqualToString:#""]?#"Please provide password":#"";
if ([_passwordField.text isEqualToString:_repeatPasswordField.text]) {
}
else
{
UIAlertView *alt = [[UIAlertView alloc]initWithTitle:#"work" message:#"Password doesn't match." delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alt show];
}
if ([str isEqualToString:#""])
{
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:_firstNameField.text,#"firstname",_lastNameField.text,#"lastname",_usernameField.text,#"username",_emailField.text,#"email",_passwordField.text,#"password", nil];
[blkRkMngr signup:dict completionBlock:^(BOOL success){
if (success) {
// Go to main menu
[self performSegueWithIdentifier:#"showMenu" sender:self];
}
else{
}
}];
}
else{
UIAlertView *alt = [[UIAlertView alloc]initWithTitle:#"LoginApp" message:str delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alt show];
}
}
Details for Signup
-(void)signup:(NSDictionary *)dictParam completionBlock:(BlackRockManagerCompletionBlock)pCompletionBlock{
NSString *strRequestUrl = KSignup;
[Helper showGlobalProgressHUDWithTitle:#"Loading"];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer.acceptableContentTypes = [operationManager.responseSerializer.acceptableContentTypes setByAddingObject:#"Text/html"];
AFHTTPRequestOperation *operation = [operationManager POST:strRequestUrl parameters:dictParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
[Helper dismissGlobalHUD];
NSDictionary* dictResponse = [NSJSONSerialization
JSONObjectWithData:operation.responseData //1
options:kNilOptions
error:nil];
NSLog(#"%#",dictResponse);
if ([[dictResponse valueForKey:#"status"] intValue] == 1) {
UIAlertView *alt = [[UIAlertView alloc]initWithTitle:#"Trend" message:[dictResponse valueForKey:#"message"] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alt show];
pCompletionBlock(YES);
}
else if([[dictResponse valueForKey:#"status"] intValue] == 2){
UIAlertView *alt = [[UIAlertView alloc]initWithTitle:#"Trend" message:[dictResponse valueForKey:#"message"] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alt show];
pCompletionBlock(NO);
}else{
UIAlertView *alt = [[UIAlertView alloc]initWithTitle:#"Trend" message:[dictResponse valueForKey:#"message"] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alt show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[Helper dismissGlobalHUD];
NSLog(#"Failed %#",operation.responseString);
}];
[operation start];
}
It's weird since I also searched everywhere in the entire code and I cannot find where the error box statement of "Username must contains only small letters and numbers".
You can not find out "Username must contains only small letters and numbers" error message because it comes from HTTP request and showed with UIAlertView.
Just checkout the codes where you request and find out why that error occurs.
I have used URLRequest to fetch a html file from a pc in my wifi network.
My app fetches a html file from my fileserver and the filename is a number which is typed in the app. Also I have given a 20 seconds timeout for the request. How can I detect whether timeout occurred because I have 2 situations,
1. file does not exist
2. connection is slow
In urlrequest, there is a BOOL for error,no description.
Suggest me a method if possible.
My code is below for only urlrequest
-(void)getHtmlContent{
[self.spinner startAnimating];
NSString *str = #"http://192.168.1.250/rec/";
// NSString *str = #"file:///Volumes/xampp/htdocs/";
str = [str stringByAppendingString:numEntered.text];
str = [str stringByAppendingString:#".html"];
NSURL *url=[NSURL URLWithString:str];
//self.htmlContent = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//NSURLRequest *request = [NSURLRequest requestWithURL:url];
request.timeoutInterval = 20.0;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
if(!error){
if([request.URL isEqual:url]){
NSString *content = [NSString stringWithContentsOfURL:localfile encoding: NSUTF8StringEncoding error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[numEntered setText:#"0"];
text = #"";
[self.spinner stopAnimating];
self.htmlContent = content;
NSString *myHTMLString = self.htmlContent;
if(myHTMLString != nil) {
if([myHTMLString isEqualToString:#"3"]){
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Success" message:#"" delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
else{
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Failed. Try again." message:#"User not authenticated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
}
});
}
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Requested file does not exist." message:#"Try again." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
}];
[task resume];
}
Since I can not comment I am writing as an Answer.
You need to check the error object to see the type of error that occured.
so in your else block you need to check error.localizedDescription to see what has happened, it would usually tell you that the file was not found or if the request timed out. you can even use your alert to show it like changing your else block as follows
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle : #"Error"
message : error.localizedDescription
delegate : self
cancelButtonTitle : #"Ok"
otherButtonTitles : nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
You must use this delegate method to handle timeout:-
-(void) connection:(NSURLConnection * ) connection didFailWithError:(NSError *)error {
if (error.code == NSURLErrorTimedOut)
// handle error as you want
NSLog(#"Request time out");
}
I need to show a UIActivityIndicatorView when calling of a WebService is take place. However, the activity indicator keeps on showing even after i have received response from web service. It stops only after 5-6 seconds after i receive response. How to make it stop at the moment i am receiving a response?
Here's my code: (configuring UIActivityIndicatorView) and calling my webservice:
loadView = [[UIView alloc] initWithFrame:self.view.bounds];
loadView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
//[second.loadingView addSubview:activityView];
//activityView.center = second.loadingView.center;
//[second.view addSubview:second.loadingView];
activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[loadView addSubview:activity];
activity.center = loadView.center;
[self.view addSubview:loadView];
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
//[activity performSelectorInBackground: #selector(startAnimating) withObject: nil];
[activity startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callRegisterWebService:self.userFname lastName:self.userLName email:self.userEmail];
});
I am stopping the animation in the finally block.
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Authentication Token Has Been Sent To Your Email-ID!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not An Authorized User" message:#"Please Contact Admin To Get Access" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
#finally {
[activity stopAnimating];
[loadView setHidden:YES];
}
}
There are 2 issues in your code:
You are manipulating UI component from a background thread, never do that. Use main thread for UI manipulations
You wrote the activity indicator functionality in the finally clause, so it'll be hidden only after executing all the statements in try clause
Change your method like:
- (void) hideActivity
{
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
[loadView setHidden:YES];
activity = nil;
loadView = nil;
});
}
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
NSString *message = #"";
NSString *title = #"";
#try
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
[self hideActivity];
if(!parsedData)
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
message = #"Authentication Token Has Been Sent To Your Email-ID!";
title = nil;
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
message = #"Please Contact Admin To Get Access";
title = #"Not An Authorized User";
}
else
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
}
}
#catch (NSException *exception)
{
if (activity != nil && loadView != nil)
{
[self hideActivity];
}
message = #"Problem In Network Connection. Please Try Again!";
title = nil;
}
#finally
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
I am tring to perform Login through JSON ,using PHP webservices , but problem is that all time its give output unvalid user what can i do??
lementation LoginViewController
NSString *username;
NSString *password;
#synthesize arr,json;
- (IBAction)btnLogin:(id)sender {
username=txtUserName.text;
password=txtPassword.text;
NSString *post = [NSString stringWithFormat:#"user_name=%#&user_password=%#",username,password];
NSLog(#"post data value is:%#",post);
NSString *hostStr =#"http://myjsonwork.com/working_apps/?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:hostStr]];
json=[NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:nil];
NSString *str=[json objectForKey:#"success"];
NSLog(#"post data value is:%#",hostStr);
NSLog(#"post dataURL value is:%#",dataURL);
if ([str isEqualToString:#"True"])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Congrats" message:#"You are //authorised" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Invalid Username and password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
}
}