LAST CHANCE: Register for my live Swift workshop days! >>

How to detect a URL in a String using NSDataDetector

Written by Paul Hudson    @twostraws

The NSDataDetector class makes it easy to detect URLs inside a string using just a few lines of code. This example loops through all URLs in a string, printing each one out:

let input = "This is a test with the URL https://www.hackingwithswift.com to be detected."
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))

for match in matches {
    guard let range = Range(match.range, in: input) else { continue }
    let url = input[range]
    print(url)
}

Available from iOS 4.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

Click here to visit the Hacking with Swift store >>