2

斯威夫特 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

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

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

4

2 回答 2

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) 
    } 
}

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

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())

输出

true 
true 
true 
true 
true 
false 
false

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

于 2019-07-26T12:01:48.743 回答
1

这是我使用的方法

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 的模式,您可以添加更多条件。

于 2019-07-26T10:16:16.567 回答