如何在 iphone 应用程序中检查 URL 是否有效,那么它应该打开它,否则它可能会显示它是无效 URL 的警报。我正在使用以下代码,但问题是如果我输入 www.google.com 它显示有效,如果我输入 nice.com 也显示有效。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(@"Test is working and test is %@",test);
if ([self urlIsValiad:test]) {
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];
}