devxoul
1/21/2016 - 6:38 PM

SWIFT: Extract URLS from String

SWIFT: Extract URLS from String

extension String {
    func extractURLs() -> [NSURL] {
        var urls : [NSURL] = []
        do {
            let detector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
            detector.enumerateMatchesInString(self,
                options: [],
                range: NSMakeRange(0, text.characters.count),
                usingBlock: { (result, _, _) in
                    if let match = result, url = match.URL {
                        urls.append(url)
                    }
            })
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return urls
    }
}