Skip to content

Instantly share code, notes, and snippets.

@ericdke
Created January 21, 2016 18:38
Show Gist options
  • Save ericdke/c4554e6c3eac01d48bd4 to your computer and use it in GitHub Desktop.
Save ericdke/c4554e6c3eac01d48bd4 to your computer and use it in GitHub Desktop.
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
}
}
@nareshdb
Copy link

nareshdb commented Sep 19, 2018

removed a warning for using characters -

extension String {
    func extractURLs() -> [URL] {
        var urls : [URL] = []
        do {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
            detector.enumerateMatches(in: self, options: [], range: NSMakeRange(0, self.count), using: { (result, _, _) in
                if let match = result, let url = match.url {
                    urls.append(url)
                }
            })
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return urls
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment