How to use WebKit WebView in SwiftUI
Developed on Xcode 11.4 with SwiftUI
Published in
2 min readApr 29, 2020
Using Any component from UIKit in SwiftUI needed to be wrapped with UIViewRepresentable. But first, we need to understand what are the basic requirement for a WKWebView.
- WebPage Loading States
- Web page title to show on navigation.
- Users can go back to the old pages.
- Delegates if needed
For Item 1–3 we need two-way binding. Where a user action(like go back to previous page etc) can be passed to WKWebView and WKWebView can pass information back so that we can update navigation and loading State.
class WebViewStateModel: ObservableObject {
@Published var pageTitle: String = "Web View"
@Published var loading: Bool = false
@Published var canGoBack: Bool = false
@Published var goBack: Bool = false
}
For Delegates, we can either use callbacks or combine. In this tutorial, I am using the callback with enum based delegation.
enum NavigationAction {
case decidePolicy(WKNavigationAction, (WKNavigationActionPolicy) -> Void) //mendetory
case didRecieveAuthChallange(URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) //mendetory
case…