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

徘徊边缘 提交于 2019-11-29 10:22:33

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.

+ (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);
}

I used this solution which is apparently a better and less complex check than a Regex check -

- (BOOL)isURL:(NSString *)inputString
{
    NSURL *candidateURL = [NSURL URLWithString:inputString];
    return candidateURL && candidateURL.scheme && candidateURL.host;
}

Try to create NSUrl with it, and see if it returns non-nil result.

if ([NSURL URLWithString:text]) {
  // valid URL
}
else {
  // invalid URL
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!