Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple SwiftUI Webview
import SwiftUI
import WebKit
struct ContentView: View {
var body: some View {
Webview(url: URL(string: "https://google.com")!)
}
}
struct Webview: UIViewRepresentable {
let url: URL
func makeUIView(context: UIViewRepresentableContext<Webview>) -> WKWebView {
let webview = WKWebView()
let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
webview.load(request)
return webview
}
func updateUIView(_ webview: WKWebView, context: UIViewRepresentableContext<Webview>) {
let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
webview.load(request)
}
}
@cmercadogallardo

This comment has been minimized.

Copy link

@cmercadogallardo cmercadogallardo commented Jan 21, 2021

How do I catch if the URL changed using your approach?

@valvoline

This comment has been minimized.

Copy link

@valvoline valvoline commented Apr 13, 2021

Something like that should work for navigation handling:

import SwiftUI
import WebKit

struct SAWebView: View {
    var body: some View {
        Webview(url: URL(string: "https://google.com")!)
    }
}

struct Webview: UIViewRepresentable {
    let url: URL
    let navigationHelper = WebViewHelper()

    func makeUIView(context: UIViewRepresentableContext<Webview>) -> WKWebView {
        let webview = WKWebView()
        webview.navigationDelegate = navigationHelper

        let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
        webview.load(request)

        return webview
    }

    func updateUIView(_ webview: WKWebView, context: UIViewRepresentableContext<Webview>) {
        let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
        webview.load(request)
    }
}

class WebViewHelper: NSObject, WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("webview didFinishNavigation")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("didStartProvisionalNavigation")
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("webviewDidCommit")
    }
    
    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        print("didReceiveAuthenticationChallenge")
        completionHandler(.performDefaultHandling, nil)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment