How to use WebKit WebView in SwiftUI

Developed on Xcode 11.4 with SwiftUI

Prafulla Singh
Mac O’Clock

--

Simulator Screenshot: Google Arts web page

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.

  1. WebPage Loading States
  2. Web page title to show on navigation.
  3. Users can go back to the old pages.
  4. 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…

--

--