WKWebView 自定义链接以在 SwiftUI 中打开 WhatsApp 等应用程序

WKWebView custom links to open apps like WhatsApp in SwiftUI

您好,我有以下代码可以在 SwiftUI Xcode12 中加载网页,一切都很好地加载,但是电话 links 和 WhatsApp link 不起作用,什么我可以做吗?

这是我的 browser.swift 文件:

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>) {
        
    }
    
}

这是我的 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()
    }
}

您需要实施 WKNavigationDelegateWKUIDelegate

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
}

添加协调器功能

func makeCoordinator() -> Coordinator {
    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)
        }
    }
}

确保在真实设备上进行测试