我想知道有没有什么方法可以在不点击 url 的情况下检测 UIWebView
中的链接?例如,如果页面有 PDF
文件,则会自动获取其链接。我知道通过 webview 的委托(delegate)我可以像这样检测点击的 url:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
if navigationType == .linkClicked
{
print(request.url?.absoluteString)
}
return true
}
但是有什么方法可以在不点击的情况下检测链接吗?
最佳答案
您可以将 NSDataDetector 用于链接类型 NSTextCheckingResult.CheckingType.link
。您只需要下载您的 url 数据并从中获取所有链接匹配:
extension String {
var detectURLs: [URL] {
return (try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue))?
.matches(in: self, range: NSRange(location: 0, length: utf16.count))
.compactMap{ $0.url } ?? []
}
}
extension Data {
var string: String { return String(data: self, encoding: .utf8) ?? "" }
}
Playground 测试:
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()
关于ios - 无需点击即可检测 UIWebView 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437670/