In SwiftUI there is not much options to load web page. We have to use UIKit component to load a page. For this purpose we need to use MKWebView and it is not a standard component in SwiftUI for loading web content. However, you can achieve this by using WKWebView
in SwiftUI.
Here is a simple example of how you can use WKWebView
in SwiftUI to load a web screen:
- First, make sure to import
WebKit
at the top of your SwiftUI file:
import WebKit
2. Create a UIViewRepresentable
struct for WKWebView
:
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)
}
}
}
3. Use the WebView
struct in your SwiftUI view:
struct ContentView: View {
var body: some View {
WebView(urlString: "your url here")
.edgesIgnoringSafeArea(.all)
}
}
In this example, when you create an instance of `WebView` and pass a URL string to it, it will load and display the web screen at that URL.