swift 5、Xcode 10、iOS 12
我的代码使用 UIApplication.shared.canOpenURL
来验证 URL,不幸的是,没有例如“http://”。
例子:
print(UIApplication.shared.canOpenURL(URL(string: "stackoverflow.com")!)) //false
print(UIApplication.shared.canOpenURL(URL(string: "http://stackoverflow.com")!)) //true
print(UIApplication.shared.canOpenURL(URL(string: "129.0.0.1")!)) //false
print(UIApplication.shared.canOpenURL(URL(string: "ftp://129.0.0.1")!)) //true
我知道 schemes 的变化(iOS9+) 并且我知道如果字符串还没有以它开头,我可以添加一个像“http://”这样的前缀,然后检查这个新字符串,但我仍然想知道:
问题:如何添加一个“没有方案”的方案,这样像“stackoverflow.com”这样的有效 URL 也会返回 true
(这甚至可能吗?) ?
最佳答案
不可能向 URL
添加有效的方案,因为没有人知道哪个前缀将添加到哪个 URL
。您可以在 regex
的帮助下验证 URL
。
我搜索并修改了正则表达式。
extension String {
func isValidUrl() -> Bool {
let regex = "((http|https|ftp)://)?((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
}
我用下面的 url 测试了它:
print("http://stackoverflow.com".isValidUrl())
print("stackoverflow.com".isValidUrl())
print("ftp://127.0.0.1".isValidUrl())
print("www.google.com".isValidUrl())
print("127.0.0.1".isValidUrl())
print("127".isValidUrl())
print("hello".isValidUrl())
Output
true
true
true
true
true
false
false
注意:100% 正则表达式无法验证 email
和 url
关于ios - 在没有方案的情况下验证 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217726/