Mega Bundle SALE is ON! Get ALL of our amazing iOS app codebases at 95% OFF discount ūüĒ•

If you’re building an application in SwiftUI and looking to incorporate web content directly into your app, a WebView is what you need. In this tutorial, we’ll walk through how to create and customize a WebView in SwiftUI.

Keywords: SwiftUI, WebView, WebKit, iOS Development, SwiftUI Views, WebView in SwiftUI

webview swiftui

Introduction

SwiftUI, Apple’s declarative UI framework, does not have a built-in WebView. However, SwiftUI allows you to integrate UIKit views, meaning we can use the WKWebView from the WebKit framework to create a WebView. Let’s learn how to do this.

Getting Started: Integrating WKWebView with SwiftUI

First, we need to create a SwiftUI View that represents a WKWebView. We can do this using the UIViewRepresentable protocol:

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let url: URL

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

    func updateUIView(_ uiView: WKWebView, context: Context) {
        // This space can be left blank
    }
}

This WebView struct takes a URL and creates a WKWebView that loads that URL.

Customizing the WebView

To customize our WebView, we can make use of the various delegate methods provided by WKWebView.

WebView Navigation Delegate

To track the loading progress of a webpage or handle navigation decisions, we can use the WKNavigationDelegate. Let’s update our WebView struct to include a Coordinator class that acts as the navigation delegate:

struct WebView: UIViewRepresentable {
    let url: URL

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        webView.load(URLRequest(url: url))
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        // This space can be left blank
    }

    class Coordinator: NSObject, WKNavigationDelegate {
        let parent: WebView

        init(_ parent: WebView) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            print("Webview started loading.")
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("Webview finished loading.")
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            print("Webview failed with error: \(error.localizedDescription)")
        }
    }
}

Now, whenever a webpage starts loading, finishes loading, or fails to load, the corresponding message will be printed to the console.

Using the WebView in your SwiftUI App

Using the WebView in your app is as simple as using any other SwiftUI View. Here’s an example:

struct ContentView: View {
    var body: some View {
        WebView(url: URL(string: "https://www.example.com")!)
    }
}

Wrapping Up

In this tutorial, we learned how to use a WebView in SwiftUI, and how to customize it to track webpage loading status. By leveraging the power of UIViewRepresentable, we can integrate virtually any UIKit view into our SwiftUI apps.

Please note that the above code has been written with Swift 5.3 and SwiftUI 2.0. If you’re using a different version, the code may need adjustments.

Conclusion

Now that you’ve mastered the basics of using a WebView in SwiftUI, you’re all set to include web content in your iOS applications more smoothly. This could include anything from loading websites to interacting with HTML interfaces directly within your application. Through the use of SwiftUI and WebKit, Apple has opened up vast possibilities for enhancing your app’s user experience.


Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart