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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With