O que voce precisa na verdade é monitorar a navegação do usuário. Voce pode fazer isso no UIWebView também mas o UIWebView ta deprecated então eu recomendo usar o WKWebView pra isso:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
print("Documents\n", FileManager.documents)
let url = URL(string: "https://www.google.com")!
webView.frame = view.bounds
webView.navigationDelegate = self
webView.load(URLRequest(url: url))
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
}
}
extension FileManager {
static let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
E implemente o metodo func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
pra detectar quando o usuario clica num link e se esse link é um pdf:
extension ViewController {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url,
url.pathExtension == "pdf" {
print("pdf url:\n", url, "\nNo need to open locally")
decisionHandler(.cancel)
// se voce quiser pode download o pdf
URLSession.shared.downloadTask(with: url) { location, response, error in
guard let location = location, let response = response else {
print("error:", error ?? "nil")
return
}
print("Location:", location.path, "\nResponse:", response, "\nFilename:", response.suggestedFilename ?? "file.pdf")
do {
let destination = FileManager.documents.appendingPathComponent(response.suggestedFilename ?? "file.pdf")
print("destination:", destination.path)
try FileManager.default.moveItem(at: location, to: destination)
print("file moved from temporary location to documents directory")
} catch {
print("File copy/move error:", error)
}
}.resume()
// ou exibir usando o safari
// if UIApplication.shared.canOpenURL(url) {
// UIApplication.shared.open(url)
// print(url)
// print("abrindo pdf com default browser")
// }
//
} else {
print("user clicked on a link that it is not a pdf")
decisionHandler(.allow)
}
} else {
decisionHandler(.allow)
}
}
}