open website in swiftui in swift

To open a website in SwiftUI, we can make use of WebKit and Safari. Here's an example code snippet using UIHostingController:

main.swift
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {

    let url: String

    func makeUIView(context: Context) -> WKWebView {
        guard let url = URL(string: self.url) else {
            return WKWebView()
        }
        
        let webView = WKWebView()
        webView.load(URLRequest(url: url))
        return webView
    }

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

struct ContentView: View {
    var body: some View {
        NavigationView {
            WebView(url: "https://google.com")
                .navigationBarTitle(Text("Google"), displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
757 chars
36 lines

In the above code, we have created a WebView struct that conforms to the UIViewRepresentable protocol. It is responsible for creating a WKWebView instance and loading the specified URL.

Then in the ContentView, we use the WebView and embed it in a NavigationView. Finally, we set the navigation bar title to show "Google".

This is just one way to open a website in SwiftUI using WebKit and Safari. There are other approaches as well, like using UIApplication.shared.open() to launch Safari directly, but this is one of the most common ways to achieve this.

gistlibby LogSnag