0

I'm making a web browser that works like any other web browser.

  • If you type text that is of freeform: "vasdfygvaosfh" it will do a Google search.

  • If you type text that has the structure of a URL: "abc.com" it will open a new page.

What is the best approach for this problem? Should I just have a couple of if statements on whether there's a dot "." present or not?

Vulkan
  • 1,004
  • 16
  • 44
  • See this [link](http://stackoverflow.com/questions/28079123/how-to-check-validity-of-url-in-swift) for basically the same question – Florensvb Feb 17 '17 at 15:36

2 Answers2

0

I use this code (a category on NSString) to check if a string is a valid URL:

- (BOOL) isValidURLString
{
    BOOL result = NO;

    if (!self.length)
        return result;

    NSError *error = NULL;
    NSDataDetector *urlDetector = [NSDataDetector dataDetectorWithTypes: NSTextCheckingTypeLink error: &error];
    NSUInteger numberOfMatches = [urlDetector numberOfMatchesInString: self
                                                              options: 0
                                                                range: NSMakeRange(0, self.length)];

    if (!error && numberOfMatches > 0)
        result = YES;

    return result;
}
koen
  • 5,383
  • 7
  • 50
  • 89
  • You're going to have to convert it to an NSURL anyway, and if the whole string isn't a URL, this will return true, but the conversion will fail. It makes more sense to just see if [NSURL URLWithString:string] returns nil. If it does, treat it as a search, else treat it as a URL. – dgatwood Feb 25 '17 at 19:24
0

You can try a regex as in:

- (BOOL)isValidURL:(NSString *)candidate{

    NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";

    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];

    return [urlTest evaluateWithObject:candidate];
}
ystack
  • 1,785
  • 12
  • 23