How to detect URL from text in Swift 2.0?

NSDataDetector is a detects semi-structured information: dates, addresses, links, phone numbers and transit information. 



There are different type of Data Detector match types. Like  NSTextCheckingTypeDate ,NSTextCheckingTypeAddress , NSTextCheckingTypeLink ,NSTextCheckingTypePhoneNumber , NSTextCheckingTypeTransitInformation etc.

How to fetch URLs from text :

1. Detect URLs by using matchesInString : 

   let text = "http://www.google.com.I am Kirit Modi, Competed Bachelor degree (Information technology). My blog url is http://iosdevcenters.blogspot.in, Check It"
        let types: NSTextCheckingType = .Link
        var URLStrings = [NSURL]()
        let detector = try? NSDataDetector(types: types.rawValue)
        let matches = detector!.matchesInString(text, options: .ReportCompletion, range: NSMakeRange(0, text.characters.count))

        for match in matches {
            print(match.URL!)
            URLStrings.append(match.URL!)
        }   print(URLStrings) 
OUTPUT IS : An array of the URLs. See Below Printed in Console.
[http://www.google.com.i, http://iosdevcenters.blogspot.in]

2. Detect URLs by using enumerateMatchesInString :

        let text = "http://www.google.com.I am Kirit Modi, Competed Bachelor degree (Information technology). My blog url is http://iosdevcenters.blogspot.in, Check It"
        let types: NSTextCheckingType = .Link
        var URLStrings = [NSURL]()
        let detector = try? NSDataDetector(types: types.rawValue)
        detector?.enumerateMatchesInString(text, options: [], range: NSMakeRange(0, (text as NSString).length)) { (result, flags, _) in
            print(result!.URL!)
            URLStrings.append(result!.URL!)
        }
        print(URLStrings)

OUTPUT IS : An array of the URLs. See Below Printed in Console.
[http://www.google.com.i, http://iosdevcenters.blogspot.in]

See more tutorials of Swift : iOSDevCenter

Thanks.
How to detect URL from text in Swift 2.0? How to detect URL from text in Swift 2.0? Reviewed by Kirit Modi on 01:46:00 Rating: 5

No comments:

Powered by Blogger.