Search code examples
iosswiftnsdatadetector

Detecting url in a text with HTTPS format


Here is my code to detect URL in a text

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
}

However, this code makes www.example.com as http://example.com

What I want is to get this URL as HTTPS like https://example.com

How can I achieve that?


Solution

  • There's no API to tell NSDataDetector to default to https URL schemes when it finds a URL with no scheme.

    One option is to update the resulting URL yourself:

    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
        }
    }