Skip to content

Instantly share code, notes, and snippets.

@awunnenb
Last active October 19, 2023 21:24
Show Gist options
  • Save awunnenb/45d4c86cf50cff0612cb242fd1061038 to your computer and use it in GitHub Desktop.
Save awunnenb/45d4c86cf50cff0612cb242fd1061038 to your computer and use it in GitHub Desktop.
SwiftUI WKWebView und WKNavigationDelegate
// 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)
}
}
}
@junmcenroe
Copy link

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

@Shayokh144
Copy link

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