Though I've successfully done this before, I can't figure it out this time. I've got a basic login screen as the first VC loaded upon launch. Successful login (appropriate username/password combo from database) does appropriately allow access without any alerts. However...any incorrect combination (or no username/password at all, for that matter), results in my desired alertView, but the next VC loads anyway. What am I doing wrong? There should be no segue at all upon failure, just an alert.

LoginViewController.m

@implementation LoginViewController

- (IBAction)unwindToLoginViewController:(UIStoryboardSegue *)unwindSegue
{
}

- (IBAction)loginClicked:(id)sender {
    NSInteger success = 0;
    @try {

        if([[self.usernameText text] isEqualToString:@""] || [[self.passwordText text] isEqualToString:@""] ) {

            [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];

        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.usernameText text],[self.passwordText text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://www.techinworship.com/auth.php"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding 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];

            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

            NSLog(@"Response code: %ld", (long)[response statusCode]);

            if ([response statusCode] >= 200 && [response statusCode] < 300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);

                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization
                                          JSONObjectWithData:urlData
                                          options:NSJSONReadingMutableContainers
                                          error:&error];

                success = [jsonData[@"success"] integerValue];
                NSLog(@"Success: %ld",(long)success);

                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                } else {

                    NSString *error_msg = (NSString *) jsonData[@"error_message"];
                    [self alertStatus:error_msg :@"Sign in Failed!" :0];
                }

            } else {
                //if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }
    if (success) {
        [self performSegueWithIdentifier:@"login_success" sender:self];
    }
}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
    [alertView show];
}
- (IBAction)backgroundTap:(id)sender {
    [self.view endEditing:YES];
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

LoginViewController.h

@interface LoginViewController : UIViewController <UITextFieldDelegate>


@property (strong, nonatomic) IBOutlet UIButton *signUpButton;
@property (strong, nonatomic) IBOutlet UIButton *forgotPasswordButton;
@property (strong, nonatomic) IBOutlet UITextField *passwordText;
@property (strong, nonatomic) IBOutlet UITextField *usernameText;

- (IBAction)loginClicked:(id)sender;
- (IBAction)backgroundTap:(id)sender;

@end
有帮助吗?

解决方案

I have found the issue. I was using the IBAction of my login button to segue between the login screen and the second VC. Because it was conditional (login success/failure), I should have CTRL clicked and dragged from the ViewController itself to the second, desired VC. Image below for example.

enter image description here

Fortunately, this was it. Rookie mistake on my part :/

其他提示

This line might be causing the possible issue. success = [jsonData[@"success"] integerValue]; It is updating success to a value greater than zero even in case of failure as well. By the way, you can do like this to solve it for now. Hopefully it will work

  • (IBAction)loginClicked:(id)sender { NSInteger success = 0; @try {

    if([[self.usernameText text] isEqualToString:@""] || [[self.passwordText text] isEqualToString:@""] ) {
    
        [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];
    
    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.usernameText text],[self.passwordText text]];
        NSLog(@"PostData: %@",post);
    
        NSURL *url=[NSURL URLWithString:@"http://www.techinworship.com/auth.php"];
    
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding 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];
    
        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
    
        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
        NSLog(@"Response code: %ld", (long)[response statusCode]);
    
        if ([response statusCode] >= 200 && [response statusCode] < 300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);
    
            NSError *error = nil;
            NSDictionary *jsonData = [NSJSONSerialization
                                      JSONObjectWithData:urlData
                                      options:NSJSONReadingMutableContainers
                                      error:&error];
    
            success = [jsonData[@"success"] integerValue];
            NSLog(@"Success: %ld",(long)success);
    
            if(success == 1)
            {
                NSLog(@"Login SUCCESS");
                [self performSegueWithIdentifier:@"login_success" sender:self];
    
            } else {
    
                NSString *error_msg = (NSString *) jsonData[@"error_message"];
                [self alertStatus:error_msg :@"Sign in Failed!" :0];
            }
    
        } else {
            //if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
        }
    }
    

    } @catch (NSException * e) { NSLog(@"Exception: %@", e); [self alertStatus:@"Sign in Failed." :@"Error!" :0]; } }

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top