不使用方案验证URL

时间:2019-07-26 10:04:05

标签: ios swift xcode url-validation

Swift 5,Xcode 10,iOS 12

我的代码使用--upx-exclude"vcruntime140.dll"来验证URL,但不幸的是,如果没有例如“ http://”。

示例:

UIApplication.shared.canOpenURL

我知道schemes(iOS9 +)的更改,并且我知道,如果String尚未以“ http://”开头,则可以添加一个前缀,例如“ http://”,然后检查此新的String,但我仍然想知道:

问题::如何添加“没有方案”方案,因此有效的URL(例如“ stackoverflow.com”)也会返回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 (这可能吗?)?

2 个答案:

答案 0 :(得分: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的模式,则可以添加更多条件。

答案 1 :(得分:1)

无法向URL添加有效的方案,因为没人知道哪个前缀将添加到哪个URL。您只需借助URL来验证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%正则表达式无法验证emailurl

相关问题