NEW: Master Swift design patterns with my latest book! >>

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 to be detected."
let detector = try! NSDataDetector(types:
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]

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.

Swift on the server is here

Get ahead of the game and learn server-side Swift with my latest book – build real-world projects while you learn!

Click here to visit the Hacking with Swift store >>