WebView in swiftUI
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
- When the app launches, SwiftUI displays the
ContentView
. - Inside
ContentView
, we useWebView
to show a web page. - The
WebView
:
- Creates a
WKWebView
(a browser view) viamakeUIView
. - Loads the URL into the
WKWebView
usingupdateUIView
.
4. The web page (https://www.apple.com
) appears inside the app!