How can I check if UISearchBar.text contains a URL? I thought of doing something like this:
if (searchBar.text == NSTextCheckingType.Link) {
}
I enhanced Imanou PETIT
's anwser.
This allows you to extract multiple URL's from a string.
extension String {
var extractURLs: [NSURL] {
var urls : [NSURL] = []
var error: NSError?
let detector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: &error)
var text = self
detector!.enumerateMatchesInString(text, options: nil, range: NSMakeRange(0, count(text)), usingBlock: { (result: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer) -> Void in
// println("\(result)")
// println("\(result.URL)")
urls.append(result.URL!)
})
return urls
}
}
An example usage:
var urls = text.extractURLs
for url in urls {
// do stuff with your URL
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
break
}
}