UIWebView Link Detection Without Click

I was wondering if there is a way to detect a link in a UIWebView without clicking on the urls? for example, if the page has a PDF file, it automatically gets its link. I know that with a webview delegate, I can detect URLs like the following:

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == .linkClicked { print(request.url?.absoluteString) } return true } 

but is there a way to detect links without a click?

0
ios iphone xcode swift uiwebview
source share
2 answers

You can use NSDataDetector for link types NSTextCheckingResult.CheckingType.link . You just need to download your URL data and get all the links from it:

 extension String { var detectURLs: [URL] { return (try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue))? .matches(in: self, range: NSRange(location: 0, length: utf16.count)) .flatMap{ $0.url } ?? [] } } extension Data { var string: String { return String(data: self, encoding: .utf8) ?? "" } } 

Playground Testing:

 import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true // add the extensions above here URLSession.shared.dataTask(with: URL(string: "http://www.example.com/downloads/")!) { data, response, error in guard let data = data, error == nil else { return } let pdfs = data.string.detectURLs.filter{$0.pathExtension.lowercased() == "pdf"} print(pdfs) // print(urls) // "[http://www.sample-videos.com/pdf/Sample-pdf-5mb.pdf]\n" }.resume() 
+2
source share

Use NSXMLParser to parse the HTML body for the UIWebView and find the a tags and get their href parameter that contains the URL.

0
source share

All Articles