Extract links from string optimization

前端 未结 7 1026
予麋鹿
予麋鹿 2021-01-03 05:21

I get data (HTML string) from website. I want to extract all links. I write function (it works), but it is so slow...

Can you help me to optimize it? What standard

7条回答
  •  日久生厌
    2021-01-03 05:33

    Very helpful thread! Here's an example that worked in Swift 1.2, based on Victor Sigler's answer.

        // extract first link (if available) and open it!
        let text = "How technology is changing our relationships to each other: http://t.ted.com/mzRtRfX"
        let types: NSTextCheckingType = .Link
    
        do {
            let detector = try NSDataDetector(types: types.rawValue)
            let matches = detector.matchesInString(text, options: .ReportCompletion, range: NSMakeRange(0, text.characters.count))
            if matches.count > 0 {
                let url = matches[0].URL!
                print("Opening URL: \(url)")
                UIApplication.sharedApplication().openURL(url)
            }
    
        } catch {
            // none found or some other issue
            print ("error in findAndOpenURL detector")
        }
    

提交回复
热议问题