验证没有方案的 URL

Nep*_*eph 2 xcode url-validation ios 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
Run Code Online (Sandbox Code Playgroud)

我知道方案(iOS9+)的变化,我知道如果字符串尚未以“http://”开头,我可以添加前缀,然后检查这个新字符串,但我仍然想知道:

问题:我如何添加“没有方案”方案,以便像“stackoverflow.com”这样的有效 URL 也返回true(这是否可能?)?

The*_*ger 6

不可能添加一个有效的方案,URL因为没有人知道哪个前缀会被添加到哪个URL. 您可以在URL的帮助下验证 a regex

我搜索并修改了正则表达式。

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) 
    } 
}
Run Code Online (Sandbox Code Playgroud)

我使用以下网址对其进行了测试:

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())
Run Code Online (Sandbox Code Playgroud)

输出

true 
true 
true 
true 
true 
false 
false
Run Code Online (Sandbox Code Playgroud)

注意: 100% 正则表达式无法验证emailurl