ios - 无需点击即可检测 UIWebView 链接

标签 ios iphone swift xcode uiwebview

我想知道有没有什么方法可以在不点击 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/

相关文章:

c++ - 如何在 XCode 4 中将旧式构建日志设置为默认构建错误 View

swift - macOS 催化剂上钥匙串(keychain)项目的 PersistentRef

ios - iTunes Connect 附上一份证明权利的契约(Contract)

ios - 如何制作 .plist 文件

ios - 如何使用 Forge 配置developer_certificate_path 和developer_certificate_password

iphone - 当我使用 COM 以编程方式同步 iphone 时让 iTunes 通知我

ios - 对齐按钮和文本的最佳方式是什么?基本的,但由于网上的错误信息是必要的

ios - 要求用户使用 swift2 从照片库或相机中选择照片

ios - 关于 Swift 中模型结构的可选绑定(bind)的问题

objective-c - objective-C 头文件中的 weak in swift 消失了