0

我正在寻找一种方法来验证一个字符串实际上是一个 URL,我非常喜欢这篇文章中的这段代码(从顶部开始第三个)如何在 Swift 中检查 URL 的有效性?

extension String {
    var isValidURL: Bool {
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        if let match = detector.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) {
            // it is a link, if the match covers the whole string
            return match.range.length == self.utf16.count
        } else {
            return false
        }
    }
}

我的第一个问题是:为什么这个开发人员选择self.utf16.count而不是选择self.utf8.count其他变体之一。

我的第二个问题是:你怎么知道这实际上是在检查它是否是一个有效的 URL?这是否符合这些要求?(NSDataDetector.link 的文档实际上是空的。+ 苹果代码中没有注释)

A URL is a valid URL if at least one of the following conditions holds:

The URL is a valid URI reference [RFC3986].

The URL is a valid IRI reference and it has no query component. [RFC3987]

The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters. [RFC3987]

The URL is a valid IRI reference and the character encoding of the URL's Document is UTF-8 or UTF-16. [RFC3987]

A string is a valid non-empty URL if it is a valid URL but it is not the empty string.

A string is a valid URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid URL.

A string is a valid non-empty URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid non-empty URL.

任何意见表示赞赏。

4

0 回答 0