0

I have another questions with WKWebView.

The following View is called with an request parameter which defines the complete url:

struct TrainerTab: UIViewRepresentable {
    
    let request: String
    private let hostingUrl: String = "https://page.tld"
    
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        let url = "\(hostingUrl)/\(request)"
        uiView.load(URLRequest(url: URL(string: url)!))
    }
}

The HTML-Files from the page.tld have some href-Links. I would like to open them in Safari. I read, that I have to implement the delegate method that gets called when the user taps a link.

But how can I do this?

Alienuser
  • 35
  • 5

1 Answers1

2

You can use a Coordinator in your UIViewRepresentatable to act as a navigation delegate for the WKWebView:

struct TrainerTab: UIViewRepresentable {
    
    let request: String
    private let hostingUrl: String = "https://page.tld"
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.navigationDelegate = context.coordinator
        let url = "\(hostingUrl)/\(request)"
        uiView.load(URLRequest(url: URL(string: url)!))
    }
    
    class Coordinator : NSObject, WKNavigationDelegate {
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            guard let url = navigationAction.request.url else {
                decisionHandler(.allow)
            }
            
            //make some conditions based on the URL here
            if myCondition {
                decisionHandler(.cancel)
                UIApplication.shared.open(url)
            } else {
                decisionHandler(.allow)
            }
        }
    }
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Ahhhh… Thank you very much! – Alienuser May 12 '21 at 20:56
  • Would you mind explaining what type of condition that could be in the "if" statement? Thank you CC: @Alienuser – oracle Oct 06 '22 at 23:23
  • 1
    @oracle Any type of condition you want. For example, does the URL start with a certain prefix or contain a certain phrase, is it it a certain time of day, etc. – jnpdx Oct 06 '22 at 23:25