这是我的代码,用于检测文本中的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一样以HTTPS形式获取此URL
我该如何实现?
答案 0 :(得分:0)
当没有找到没有方案的URL时,没有API告诉NSDataDetector
默认为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
}
}