ios - 在没有方案的情况下验证 URL

标签 ios swift xcode url-validation

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% 正则表达式无法验证 emailurl

关于ios - 在没有方案的情况下验证 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217726/

相关文章:

ios - UIImage 类型的值必须为 bindTo

javascript - Mobile safari : frame. src 与 window.location

swift - 我如何每第 n 次尝试做某事?

ios - 打开网址并留在应用程序中

iphone - 通过 Bonjure Logic 问题可靠地发送大文件

ios - 我的打电话功能出了什么问题

ios - 如何将一张图片放在另一张图片前面?

xcode - iOS sdk,从无符号字符数组渲染图像,CGBitmapContextCreate 返回 NULL

objective-c - 如何解决 NSInternalInconsistencyException',原因 : '+entityForName: fail report

objective-c - 在 ARC 下的 Cocoa 中,我可以获得引用另一个对象的对象列表(以编程方式或使用仪器)?