open website swiftui in swift

To open a website within a Swift app using SwiftUI, you can use the WKWebView component. Here's an example of how to create a WKWebView and load a website:

main.swift
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let urlString: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            uiView.load(request)
        }
    }
}

struct ContentView: View {
    var body: some View {
        WebView(urlString: "https://www.google.com")
    }
}
504 chars
24 lines

In the above code, we first create a WebView struct that conforms to the UIViewRepresentable protocol. We define urlString as a parameter that is used to specify the URL of the website to load.

In the makeUIView method, we return an instance of WKWebView. In the updateUIView method, we check if the urlString is a valid URL and, if so, we create a URLRequest and load it into the WKWebView.

Finally, in the ContentView struct, we create an instance of WebView and pass in the URL of the website we want to open. With these steps, we can easily open a website within our SwiftUI app.

related categories

gistlibby LogSnag