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) | |
} | |
} | |
} |
this code helps me a lot. thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dear awunnenb
I am now study swiftui, and this code is very helpful for me.
I would like to define the URL address as some variable which user can change in text field. How should I change code?
Currently your program is hard coding for address
"WebView(request: URLRequest(url: URL(string: "https://www.google.com")!))"
Can you suggest me how to change?
Best Regards