Last active
October 19, 2023 21:24
-
-
Save awunnenb/45d4c86cf50cff0612cb242fd1061038 to your computer and use it in GitHub Desktop.
SwiftUI WKWebView und WKNavigationDelegate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// YouTube Video: https://youtu.be/o52XYvwTQU0 | |
import SwiftUI | |
import WebKit | |
struct ContentView: View { | |
let webView = WebView(request: URLRequest(url: URL(string: "https://www.google.com")!)) | |
var body: some View { | |
VStack { | |
webView | |
} | |
} | |
} | |
struct WebView: UIViewRepresentable { | |
let request: URLRequest | |
private var webView: WKWebView? | |
init(request: URLRequest) { | |
self.webView = WKWebView() | |
self.request = request | |
} | |
func makeUIView(context: Context) -> WKWebView { | |
return webView! | |
} | |
func updateUIView(_ uiView: WKWebView, context: Context) { | |
uiView.navigationDelegate = context.coordinator | |
uiView.load(request) | |
} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
class Coordinator: NSObject, WKNavigationDelegate { | |
let parent: WebView | |
init(_ parent: WebView) { | |
self.parent = parent | |
} | |
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { | |
if let host = navigationAction.request.url?.host { | |
if (host != "www.google.com") && (navigationAction.navigationType == .linkActivated) { | |
UIApplication.shared.open(navigationAction.request.url!) | |
decisionHandler(.cancel) | |
return | |
} | |
} | |
decisionHandler(.allow) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this code helps me a lot. thank you.