我有一个应用程序,我希望当用户在文本字段中输入 url 并按返回键时,它应该检查 url 是否有效,然后在 web 视图中加载 url 否则显示警报输入有效 url
在我的代码中,它始终显示有效 URL。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(@"Test is working and test is %@",test);
[self urlIsValiad:test];
if ([test isEqualToString:@"Valid"]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please enter Valid URL" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}
- (BOOL) urlIsValiad: (NSString *) url
{
NSString *regex =
@"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this
///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,@?^=%&:/~+#]* [\w-\@?^=%&/~+#])?";
NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([regextest evaluateWithObject: url] == YES) {
NSLog(@"URL is valid!");
test=@"Valid";
} else {
NSLog(@"URL is not valid!");
test=@"Not Valid";
}
return [regextest evaluateWithObject:url];
}