WKWebView custom links to open apps like WhatsApp in SwiftUI

Viewed 1099

Hi i have the following code to load a webpage in SwiftUI Xcode 12, everything load nicely, but the tel links and WhatsApp link doesn't work, what can I do?

this is my browser.swift file:

import Foundation
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable{
    var url: String
    func makeUIView(context: Context) -> some WKWebView {
        guard let url = URL(string: self.url) else {
            return WKWebView()
        }
        let request = URLRequest(url: url)
        let wkWebView = WKWebView()
        wkWebView.load(request)
        return wkWebView
    }
    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<WebView>) {
        
    }
    
}

this is my contentview.swift:

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
        Color(UIColor(red: 0.89, green: 0.98, blue: 0.88, alpha: 1.00))
                                .ignoresSafeArea()
                            
        WebView(url: "https://dominio.com/app/ios/index.php?idE=17")
            
        }
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
1 Answers

You need to implement the WKNavigationDelegate and WKUIDelegate

func makeUIView(context: Context) -> some WKWebView {
    guard let url = URL(string: self.url) else {
        return WKWebView()
    }
    
    let request = URLRequest(url: url)
    let wkWebView = WKWebView()
    
    wkWebView.navigationDelegate = context.coordinator //<<Add your delegates here
    wkWebView.uiDelegate = context.coordinator //<<Add your delegates here

    wkWebView.load(request)
    return wkWebView
}

Add your coordinator function

func makeCoordinator() -> Coordinator {
    Coordinator()
}

And at the Coordinator class

class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
    {
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        
        if navigationAction.request.url?.scheme == "tel" {
            UIApplication.shared.openURL(navigationAction.request.url!)
            decisionHandler(.cancel)
        }
        else if navigationAction.request.url?.scheme == "mailto" {
            UIApplication.shared.openURL(navigationAction.request.url!)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
}

Make sure to test it on real devices

Related