What you really need is to monitor the user's navigation. You can do this in UIWebView too but UIWebView is deprecated so I recommend using WKWebView for this:
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!
}
And implement the func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
method to detect when the user clicks a link and if that link is a 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)
}
}
}