donkey
donkey

Reputation: 1448

if statement returns TRUE when it should be FALSE on UIWebView request URL

I have a series of if statement s to check whether I'm logged in or not.

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    if ([webView.request.URL isEqual:@"http://www.tapgram.com/login"]) {

        NSLog(@"on log in page: %@", webView.request.URL);


    } else if ([webView.request.URL isEqual:@"http://www.tapgram.com/loginfailed?alert_message=Failed+login&came_from=%2F"]){

        NSLog(@"failed log in: %@", webView.request.URL);

        [keychainItem resetKeychainItem];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Incorrect Credentials" message:@"It seems that either your username or password is incorrect. Please try agian." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

        [alert show];

    } else if (![webView.request.URL isEqual:@"http://www.tapgram.com/login"]) {

        NSLog(@"logged in: %@", webView.request.URL);

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];

        [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

        [self presentViewController:vc animated:YES completion:nil];
    }

I get this log:

2013-12-22 21:58:02:054 Tapgram[1096:1547] -[LogInViewController webViewDidFinishLoad:] [Line 151] logged in: http://www.tapgram.com/login

Which means that one of the if statements saying if(![webView.request.URL isEqual:@"http://www.tapgram.com/login"]) returns TRUE when the URL is equal to the one specified. And the NSLog in the if statement proves it.

Upvotes: 0

Views: 209

Answers (2)

Sti
Sti

Reputation: 8484

You can convert the NSURL to an NSString for string-comparison by adding .absoluteString and using isEqualToString: rather than isEqual:, like this:

if ([webView.request.URL.absoluteString isEqualToString:@"http://www.example.com/test"])

Upvotes: 1

Lucas Derraugh
Lucas Derraugh

Reputation: 7049

You're comparing an NSURL object to an NSString, so they aren't the same. You can convert the NSURL object (webView.request.URL) to a string by using NSURL's -absoluteString and compare those or create an NSURL object out of the NSString and compare those.

As an example, you can't compare an NSURL and an NSString object directly. You can use the absoluteString though to compare:

NSString *string = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:string];
NSURL *url2 = [NSURL URLWithString:string];
if ([url isEqual:string]) {
    NSLog(@"String Equal");
} if ([url isEqual:url2]) {
    NSLog(@"URL Equal");
} if ([url.absoluteString isEqualToString:string]) {
    NSLog(@"Absolute String Equal");
}

Outputs:

URL Equal
Absolute String Equal

Upvotes: 5

Related Questions