How to quickly check if an NSString object is a valid URL?

Help me write code like "if my string is a valid URL, can this be written in a couple of lines of code?

+7
source share
5 answers

I assume that at the URL you are referring to a string identifying the location of the Internet resource.

If you have an idea of ​​the format of the input string, 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 checklist (e.g. ftp:// , mailto:// , etc.)

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

If you are looking for a more robust solution and find some kind of URL pattern, you should use a regex.

As an additional note, the NSURL class is intended to express any kind of resource location (and not just Internet resources). This is why lines like img/demo.jpg or file://bla/bla/bla/demo.jpg can be converted to NSURL objects.

However, according to the documentation, [NSURL URLWithString] should return nil if the input string is not a valid Internet resource string. In practice, this is not so.

+19
source

I used this solution, which seems to be better and less complicated than a Regex check -

 - (BOOL)isURL:(NSString *)inputString { NSURL *candidateURL = [NSURL URLWithString:inputString]; return candidateURL && candidateURL.scheme && candidateURL.host; } 
+7
source
 + (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); } 
+6
source

Try creating an NSUrl with it and see if it returns a non-zero result.

+1
source
 if ([NSURL URLWithString:text]) { // valid URL } else { // invalid URL } 
0
source

All Articles