在 HTTPS 格式的文本中检测 url
Detecting url in a text with HTTPS format
这是我用来检测文本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
我想要的是像 https://example.com
一样将此 URL 作为 HTTPS
我怎样才能做到这一点?
没有 API 告诉 NSDataDetector
在找到没有方案的 URL 时默认使用 https
URL 方案。
一个选项是自己更新结果 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
}
}
这是我用来检测文本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
我想要的是像 https://example.com
一样将此 URL 作为 HTTPS我怎样才能做到这一点?
没有 API 告诉 NSDataDetector
在找到没有方案的 URL 时默认使用 https
URL 方案。
一个选项是自己更新结果 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
}
}