Skip to content

Instantly share code, notes, and snippets.

@ArchieGoodwin
Created February 9, 2023 10:05
Show Gist options
  • Save ArchieGoodwin/eaf3e1505c4cec500c640d2b56de2ec6 to your computer and use it in GitHub Desktop.
Save ArchieGoodwin/eaf3e1505c4cec500c640d2b56de2ec6 to your computer and use it in GitHub Desktop.
WKWebView helper class for SwiftUI with support of detecting url redirect
import SwiftUI
import WebKit
typealias WebCallBack = ((String?) -> Void)?
class MyWKDelegate: NSObject, WKNavigationDelegate {
private var webCallBack: WebCallBack = nil
init(webCallBack: WebCallBack) {
self.webCallBack = webCallBack
}
func webView(_: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
webCallBack?(navigationAction.request.url?.absoluteString)
decisionHandler(.allow)
}
func webView(_: WKWebView, didFinish _: WKNavigation!) {
print("End loading")
}
}
class MyScriptDelegate: NSObject, WKScriptMessageHandler {
func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
print("WKScriptMessageHandler", message.body)
}
}
struct WebView: UIViewRepresentable {
let webView: WKWebView
let delegate: MyWKDelegate
internal init(urlStr: String, webCallBack: WebCallBack) {
let config = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: config)
delegate = MyWKDelegate(webCallBack: webCallBack)
webView.navigationDelegate = delegate
if let url = URL(string: urlStr) {
webView.load(URLRequest(url: url))
}
}
private func getConfiguredWebview() -> WKWebView {
return webView
}
func makeUIView(context _: Context) -> WKWebView {
return webView
}
func updateUIView(_: WKWebView, context _: Context) {}
}
//Usage
WebView(urlStr: "some url", webCallBack: { (d: String?) in
print(d)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment