Created
January 21, 2016 18:38
-
-
Save ericdke/c4554e6c3eac01d48bd4 to your computer and use it in GitHub Desktop.
SWIFT: Extract URLS from String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
The Update for Swift 3 works for Swift 4.1 too.