Swift: check if UISearchBar.text contains a url

后端 未结 2 1768
野性不改
野性不改 2021-01-24 15:37

How can I check if UISearchBar.text contains a URL? I thought of doing something like this:

if (searchBar.text == NSTextCheckingType.Link) {

}

2条回答
  •  北海茫月
    2021-01-24 15:59

    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
         }
    }
    

提交回复
热议问题