2

I am trying to validate strings as proper URL's that can conform to a format of one of the following

  • www.site.domain...(any structure that is legal)
  • http(s)://site.domain...(any structure that is legal)
  • http(s)://site.domain...(any structure that is legal)

problem is that it is validating text

http://cat

which is clearly bad.

My code is:

BOOL isReachable = [self validateIsReachable:text];
    if (!isReachable)
    {
        if ([text hasPrefix:@"http://"] || [text hasPrefix:@"https://"])
        {
            BOOL valid = [NSString validateUrlString:text];
            if (!valid)
            {
                                // need to do something...
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bad url" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                return;
            }

        } else {
            text = [NSString stringWithFormat:@"http://%@",text];
            isReachable = [self validateIsReachable:text];
            if (!isReachable)
            {
                                // need to do something
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bad url" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                return;
            }
        }
    }

    NSURLRequest *request = [self requestForString:text];
    [self.webView loadRequest:request];
}

-(BOOL)validateIsReachable:(NSString *)text
{
    return [NSString isValidUrl:text];



+(BOOL)isValidUrl:(NSString *)candidate
{
    NSURL *candidateURL = [NSURL URLWithString:candidate];
    // WARNING > "test" is an URL according to RFCs, being just a path
    // so you still should check scheme and all other NSURL attributes you need
    NSString *scheme = candidateURL.scheme;
    NSString *host = candidateURL.host;
    BOOL v = [NSString validateUrlString:candidate];
    if (candidateURL && candidateURL.scheme && candidateURL.host) {
        // candidate is a well-formed url with:
        //  - a scheme (like http://)
        //  - a host (like stackoverflow.com)
        return YES;
    }
    return NO;
}

+(BOOL)validateUrlString:(NSString*)urlString
{
    if (!urlString)
    {
        return NO;
    }

    NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];

    NSRange urlStringRange = NSMakeRange(0, [urlString length]);
    NSMatchingOptions matchingOptions = 0;

    if (1 != [linkDetector numberOfMatchesInString:urlString options:matchingOptions range:urlStringRange])
    {
        return NO;
    }

    NSTextCheckingResult *checkingResult = [linkDetector firstMatchInString:urlString options:matchingOptions range:urlStringRange];

    return checkingResult.resultType == NSTextCheckingTypeLink
    && NSEqualRanges(checkingResult.range, urlStringRange);
}

when loading the webpage - UIWebview delegate invokes

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
// NSURLErrorDomain - A server with the specified hostname could not be found
    if (error.code == -1003)
    {
      // bad domain or unreachable (valid url structure but host isn't around)
    }
}

if the host is unreachable I want to take the host name and perform a google search on it

for instance in the case where it is validating

http://cat

I want to extract cat

But in the case where it is

http://<www>cat.com(or any proper domain) 

I want to show an error that the host is actually unreachable

Kumar KL
  • 15,315
  • 9
  • 38
  • 60
Avba
  • 14,822
  • 20
  • 92
  • 192
  • 1
    Why is it so important to validate the URL? Why not attempt to access the resource defined by the URL and you will know fairly quickly if it's valid or not. – trojanfoe Feb 03 '14 at 10:55
  • because nsurlrequest will fail if you input : www.cat.com because there is no "http://" before – Avba Feb 03 '14 at 10:56
  • Then you know it's not valid. Isn't that "job done"? – trojanfoe Feb 03 '14 at 10:58

2 Answers2

0

Try using NSUrl's host:

  NSURL *URL = [NSURL URLWithString:url];
  NSLog(@"%@", [URL host]);

Using this you will get the respected host name which you can show in your error. Please read the documentation as well.

Hope it helps!

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
0

try this check for valiation

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

reference link

Community
  • 1
  • 1
Pawan Rai
  • 3,434
  • 4
  • 32
  • 42