Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly check if NSString object is a valid url?

Help me to write the code like "if my string is a valid URL do smth" Is it possible to write this in a couple strings of code?

like image 775
Stas Avatar asked Feb 13 '12 12:02

Stas


2 Answers

I will assume that by URL, you are referring to a string identifying a internet resource location.

If you have an idea about the format of the input string , then why not manually check if the string starts with http://, https:// or any other scheme you need. If you expect other protocols, you can also add them to the check list (e.g. ftp://, mailto://, etc)



if ([myString hasPrefix:@"http://"] || [myString hasPrefix:@"https://"])
{
    // do something
}

If you are looking for a more solid solution and detect any kind of URL scheme, then you should use a regular expression.

As a side note, the NSURL class is designed to express any kind of resource location (not just internet resources). That is why, strings like img/demo.jpg or file://bla/bla/bla/demo.jpg can be transformed into NSURL objects.

However, according to the documentation the [NSURL URLWithString] should return nil if the input string is not a valid internet resource string. In practice it doesn't.

like image 75
Andrei Stanescu Avatar answered Nov 15 '22 20:11

Andrei Stanescu


+ (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);
}
like image 42
MarkII Avatar answered Nov 15 '22 20:11

MarkII