top of page

31. SwiftUI: Introducing WebKit

Writer's picture: Hui WangHui Wang

Today I will show you how to use view controls from other frameworks in the SwiftUI project.

SwiftUI doesn't provide a web view, so we need to use the web view in WebKit.


Steps:

  • First, we need to import the WebKit framework.

  • Make the current struct conform to the UIViewRepresentable protocol. With this protocol, UIView objects can be created and managed in SwiftUI.

  • Implement the makeUIView method in the protocol to initialize and return a WKWebView.

  • Then implement the updateUIView method in the protocol to set the URL parameters that the web view needs to load.

  • Initialize a URLRequest object as the URL of the web view.

  • Load the corresponding web page through the load method.




Source Code:

import SwiftUI
import WebKit

struct ContentView: UIViewRepresentable {
    
    func makeUIView(context: UIViewRepresentableContext<ContentView>) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<ContentView>) {
        let request = URLRequest(url: URL(string: "https://www.podnu.com/")!)
        uiView.load(request)
    }
}

 

Follow me on:

Comments


Never Miss a Post. Subscribe Now!

I am an iOS developer, and I will share some knowledge related to iOS development from time to time.

Thanks for submitting!

© 2022 by (Foks) Hui Wang

bottom of page