这是我使用的方法
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])
}
}
显然代码中的方法名和注释不够冗长,这里就解释一下。
使用NSDataDetector并为其提供类型 - NSTextCheckingResult.CheckingType.link来检查链接。
这将遍历提供的字符串并返回 URL 类型的所有匹配项。
这将检查您提供的字符串中的链接(如果有),否则返回 nil。
getURLIfPresent方法从该字符串返回 URL 部分。
这里有一些例子
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())
输出
Optional("http://stackoverflow.com")
Optional("stackoverflow.com")
Optional("ftp://127.0.0.1")
Optional("www.google.com")
nil
nil
nil
但是,对于“127.0.0.1”,这不会返回 true。所以我不认为它会满足你的事业。在您的情况下,采用正则表达式方式似乎更好。如果您遇到更多需要被视为 URL 的模式,您可以添加更多条件。