This is the method that I use
extension String {
/// Return first available URL in the string else nil
func checkForURL() -> NSRange? {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return nil
}
let matches = detector.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))
for match in matches {
guard Range(match.range, in: self) != nil else { continue }
return match.range
}
return nil
}
func getURLIfPresent() -> String? {
guard let range = self.checkForURL() else{
return nil
}
guard let stringRange = Range(range,in:self) else {
return nil
}
return String(self[stringRange])
}
}
Apparently, the method name and the comment in the code are not verbose enough, so here is the explanation.
Used NSDataDetector and provided it the type - NSTextCheckingResult.CheckingType.link to check for links.
This goes through the string provided and returns all the matches for URL type.
This checks for link in the string that you provide, if any, else returns nil.
The method getURLIfPresent return the URL part from that string.
Here are a few examples
print("http://stackoverflow.com".getURLIfPresent())
print("stackoverflow.com".getURLIfPresent())
print("ftp://127.0.0.1".getURLIfPresent())
print("www.google.com".getURLIfPresent())
print("127.0.0.1".getURLIfPresent())
print("127".getURLIfPresent())
print("hello".getURLIfPresent())
Output
Optional("http://stackoverflow.com")
Optional("stackoverflow.com")
Optional("ftp://127.0.0.1")
Optional("www.google.com")
nil
nil
nil
But, this doesn't return true for "127.0.0.1". So I don't think it will fulfil your cause.
In your case, going the regex way is better it seems. As you can add more conditions if you come across some more patterns that demand to be considered as URL.
scheme
if not exists in theURL
? – Murrayhttp://190.128.0.1
exists andftp://190.128.0.1
doesn't. In that case is190.128.0.1
valid or invalid ? – Murray[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$
I found this regex for you which validates like this. – Murray