Web View in SwiftUI

Chase
2 min readApr 15, 2024

In this article, we will add a web view to SwiftUI (even though one doesn’t exist yet). It’s easier than you might think.

The text of SwiftUI WebView above a Swift logo next to a compass icon

Before we get started, please take a couple of seconds to follow me and 👏 clap for the article so that we can help more people learn about this useful content.

Building our component

While SwiftUI doesn’t yet have a built-in web view component, we can use the UIKit version to build our own SwiftUI component using UIViewRepresentable. The init method isn’t required, but allows the call site of our custom view to be a little cleaner. One good thing about implementing the code in this way is that our example is backward compatible with older versions of iOS.

//  WebView.swift
import Foundation
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
let url: URL

init(_ url: URL) {
self.url = url
}

func makeUIView(context: Context) -> some UIView {
let webView = WKWebView()
webView.load(URLRequest(url: url))

return webView
}

func updateUIView(_ uiView: UIViewType, context: Context) {}
}

As we can see, our call site simply takes the URL that we want to display. In a production app, we would want to ensure that the string is a real URL before trying to render the view, however, I copied and pasted the URL so I know it is a good URL which is why this example is using force unwrapping.

//  ContentView.swift
import SwiftUI

struct ContentView: View {
var body: some View {
VStack {
WebView(URL(string: "https://medium.com/@jpmtech")!)
}
}
}

#Preview {
ContentView()
}

Running this code in the simulator, we get the following image.

A screenshot of the web view that we built in this tutorial

If you got value from this article, please consider following me, 👏 clapping for this article, or sharing it to help others more easily find it.

If you have any questions on the topic or know of another way to accomplish the same task, feel free to respond to the post or share it with a friend and get their opinion on it. If you want to learn more about native mobile development, you can check out the other articles I have written here: https://medium.com/@jpmtech. If you want to see apps that have been built with native mobile development, you can check out my apps here: https://jpmtech.io/apps. Thank you for taking the time to check out my work!

--

--