0

这是我在文本中检测 URL 的代码

let detector: NSDataDetector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches: [NSTextCheckingResult] = detector.matches(in: message!, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, (message?.count)!))
var url: URL?
for item in matches {
    let match = item as NSTextCheckingResult
    url = match.url
    print(url!)
    break
}

但是,此代码使 www.example.com 成为http://example.com

我想要的是将此 URL 作为 HTTPS 获取,例如https://example.com

我怎样才能做到这一点?

4

1 回答 1

0

当它找到一个没有方案的 URL 时,没有 API 可以告诉NSDataDetector它默认为httpsURL 方案。

一种选择是自己更新生成的 URL:

let message = "www.example.com"
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: message, range: NSRange(location: 0, length: message.utf16.count))
var url: URL?
for match in matches {
    if match.resultType == .link {
        url = match.url
        if url?.scheme == "http" {
            if var urlComps = URLComponents(url: url!, resolvingAgainstBaseURL: false) {
                urlComps.scheme = "https"
                url = urlComps.url
            }
        }
        print(url)
        break
    }
}
于 2018-11-28T19:06:41.630 回答