我有一系列if语句来检查我是否已登录。
- (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];
}
我得到这个日志:
2013-12-22 21:58:02:054 Tapgram [1096:1547] - [LogInViewController webViewDidFinishLoad:] [第151行]登录:http://www.tapgram.com/login
这意味着当URL等于指定的URL时,其中一个if语句将if(![webView.request.URL isEqual:@"http://www.tapgram.com/login"])
返回TRUE。 if语句中的NSLog证明了这一点。
答案 0 :(得分:5)
您正在将NSURL对象与NSString进行比较,因此它们不同。您可以使用NSURL的-absoluteString将NSURL对象(webView.request.URL)转换为字符串,然后比较它们或从NSString中创建NSURL对象并进行比较。
例如,您无法直接比较NSURL和NSString对象。您可以使用absoluteString进行比较:
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");
}
输出:
URL Equal
Absolute String Equal
答案 1 :(得分:1)
您可以通过添加.absoluteString
并使用isEqualToString:
而不是isEqual:
将NSURL转换为NSString进行字符串比较,如下所示:
if ([webView.request.URL.absoluteString isEqualToString:@"http://www.example.com/test"])