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



嗨,我有以下代码来在SwiftUI Xcode 12中加载网页,一切都加载得很好,但电话链接和WhatsApp链接不起作用,我该怎么办?

这是我的浏览器.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>) {

}

}

这是我的内容视图。wift:

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

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

相关内容

  • 没有找到相关文章

最新更新