WebView in swiftUI

Nitish Kumar
1 min readDec 28, 2024

--

Currently, SwiftUI doesn’t include all the views that UIKit provides. One such missing view is a WebView for displaying web content.

To bridge this gap, we can use UIViewRepresentable, a protocol that allows us to integrate UIKit views (like WKWebView) into SwiftUI.

Let’s break it down and create a WebView in SwiftUI using UIViewRepresentable.

import SwiftUI
import WebKit

// WebView implementation
struct WebView: UIViewRepresentable {
let url: URL

func makeUIView(context: Context) -> WKWebView {
// Create the WKWebView instance
WKWebView()
}

func updateUIView(_ webView: WKWebView, context: Context) {
// Load the requested URL
let request = URLRequest(url: url)
webView.load(request)
}
}

WKWebView is a browser-like view for displaying web pages.

The makeUIView and updateUIView methods let SwiftUI and UIKit communicate.

// ContentView
struct ContentView: View {
var body: some View {
NavigationView {
WebView(url: URL(string: “https://www.apple.com")!)
.navigationTitle(“Apple”)
.navigationBarTitleDisplayMode(.inline)
}
}
}

// Preview
#Preview {
ContentView()
}

How It All Works Together

  1. When the app launches, SwiftUI displays the ContentView.
  2. Inside ContentView, we use WebView to show a web page.
  3. The WebView:
  • Creates a WKWebView (a browser view) via makeUIView.
  • Loads the URL into the WKWebView using updateUIView.

4. The web page (https://www.apple.com) appears inside the app!

Thanks, Happy coding :)

--

--

Nitish Kumar
Nitish Kumar

Written by Nitish Kumar

I developed and maintain applications aimed at a range of iOS devices including mobile phones and tablet computers.

No responses yet