Sunday, 8 September 2013

how to validate URL in iphone app

how to validate URL in iphone app

How to check in iphone app that if URL is valid then it should open it
other wise it may show alert that it is invalid URL.I am using following
code but problem is that if i enter www.google.com it shows valid if i
enter nice.com also it show valid.
- (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];
}

No comments:

Post a Comment