0

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];
 }
Queen Solutions
  • 253
  • 2
  • 5
  • 17

5 Answers5

6

There is an in-built function, named canOpenURL is available in UIApplication class.

This will return true/false, if iOS safari can open that URL or not.

BOOL canOpenGivenURL = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:resultText]];

if (canOpenGivenURL) {

    // URL is valid, open URL in default safari browser
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultText]];

    // write your code here
}
else
    // Not valid URL -- show some alert 

Instead of validating all the available URL types, this would be easier to validate.

Hope this helps.

Mrunal
  • 13,982
  • 6
  • 52
  • 96
5

If you want to check URL is valid or not then use following RegEx.

NSString *urlString = [NSString stringWithFormat:@"URL_STRING"];
NSString *urlRegEx =
    @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlPredic = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
BOOL isValidURL = [urlPredic evaluateWithObject:urlString];

And put condition such like

if(isValidURL)
{
  // your URL is valid;
}
else
{
  // show alert message for invalid URL;
}

And also your can convert URL as legal URL, such like

NSString *urlString = [NSString stringWithFormat:@"URL_STRING"];
NSURL *youURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

For more information check stringByAddingPercentEscapesUsingEncoding:

iPatel
  • 46,010
  • 16
  • 115
  • 137
  • iPatel it is ok it shows valid or not valid but if url is valid in iphone but does not have any things it show 404 on normal pc how to check if url has 404 then it is invalid – Queen Solutions Sep 09 '13 at 06:04
  • @QueenSolutions - http://stackoverflow.com/questions/1404366/check-if-nsurl-returns-404 – iPatel Sep 09 '13 at 06:10
2

You can check with this

-(BOOL)isValidURL
{
    BOOL isValidURL = NO;   
    NSURL *candidateURL = [NSURL URLWithString:self];
    if (candidateURL && candidateURL.scheme && candidateURL.host)
        isValidURL = YES;
    return isValidURL;
}

and test like this

if([YOUR_TEXTFIELD.text isValidURL]){
   NSLog(@"Valid URL");
}
Mehul Mistri
  • 15,037
  • 14
  • 70
  • 94
1

While I admire the effort to find a regular expression to validate a URL, it is generally NOT sufficient when you want to use this URL to actually access resources. Syntactically, it may turn out to be correct, nonetheless there are countless reasons why this url won't work with the server anyway - for example, a unrecognized token in a query string which the server rejects.

This "validation" may be helpful, if you want to prevent that arbitrary junk will be entered which should look like an url, for example when you want save this url in a database. But it is pointless when you want to use it immediately to load a resource.

In your case, it is NOT sufficient to check if a URL "is syntactically valid". The only way to find out is to actually use it and return an error code when the attempt to load the resource fails. Thinking that validation beforehand would you save something isn't true, it's an unnecessary cost when the url is valid and works.

So, basically change your approach as follows:

  1. Use asynchronous methods to return the result
  2. Check for errors
CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67
0

If you want to Check url with http:// then you can use below regular expiration. Example :

  1. http://www.example.com --- True
  2. www.example.com --- False
  3. example.com --- False

-(BOOL) validateUrl: (NSString *) candidate {
    NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
    return [urlTest evaluateWithObject:candidate];
}

If you want to fix www. in URL then you can use this regular expiration.

Example :

  1. www.example.com --- True
  2. example.com --- False
  3. http://www.example.com --- False

 NSString *urlRegEx =  @"(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";

-(BOOL) validateUrl: (NSString *) candidate {
    NSString *urlRegEx =  @"(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
    return [urlTest evaluateWithObject:candidate];
}
  • What if I want True for all three cases & then create their valid `NSURL` objects ? – Mrug Sep 02 '16 at 06:26