SwiftSwiftUIAppleSnippet
Last updated at 2023-07-25

How to Show WebView in SwiftUI

ClickUp
Note
AI Status
Last Edit By
Last edited time
Jul 25, 2023 03:38 AM
Metatag
Slug
how-to-show-webview-swiftui
Writer
Published
Published
Date
Jul 22, 2023
Category
Swift
SwiftUI
Apple
Snippet
One of the essential components in a mobile application is a WebView. This component allows you to show common screens that are usually implemented using web technologies, such as terms of service, privacy policy, or even a login screen.
If you are a UIKit developer, implementing a WebView is easy. However, using SwiftUI, it turns out to be a little difficult. There is no native way to show a WebView in SwiftUI. There is no such native WebView view in SwiftUI.
The only available solution to show a WebView natively is using Link which redirects the user to the Safari app, which is not what you want.
You need to show an in-app WebView screen rather than taking the user out of the application.
There is a solution to the above problem. SwiftUI provides you with UIViewRepresentable. This protocol allows you to build a view that uses a UIKit view.
In this tutorial, you will learn how to integrate UIKit WKWebView into SwiftUI using UIViewRepresentable.

How to Show WKWebView in SwiftUI

Bridging WKWebView to SwiftUI using UIViewRepresentable

First you need to create a new SwiftUI view called WebView and use WKWebView under the hood.
import SwiftUI import WebKit struct WebView: UIViewRepresentable { let url: URL func makeUIView(context: Context) -> WKWebView { return WKWebView() } func updateUIView(_ webView: WKWebView, context: Context) { let req = URLRequest(url: url) webView.load(req) } }
That’s it. Now you can show WKWebView in SwiftUI

Using new WebView in SwiftUI

Now that you already have WebView view, you can use it in your SwiftUI screen
In this code, you will show this blog article in WebView.
struct ContentView: View { var body: some View { WebView(url: URL(string: "https://www.mozzlog.com/blog/easy-lazyhgrid-for-horizontal-collection-view")!) } }

Conclusion

Currently there is no native SwiftUI view to show WebView screen. But SwiftUI already provides a protocol that enable you to show WKWebview. Integrating WKWebView into SwiftUI can be done using UIViewRepresentable.

Discussion (0)

Related Posts