Peter Van de Put
Peter Van de Put

Reputation: 938

How to use a WKWebview with latest version of SwiftUI?

Previously I used the following code to render HTML in a view with swiftUI

import WebKit

struct HTMLView: UIViewRepresentable {
    let htmlString:String
    func makeUIView(context:Context)->WKWebView{
        return WKWebView()
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlString, baseURL: nil)
        uiView.isOpaque = false
    }
}

struct HTMLView: UIViewRepresentable {
    let htmlString:String
    func makeUIView(context:Context)->WKWebView{
        return WKWebView()
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlString, baseURL: nil)
        uiView.isOpaque = false
    }
}
extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

and i my view I use it like this

    HTMLView(htmlString: "<html<<head><style>body{font-size:36px;color:#2282b2;blockquote {margin: 0 auto;padding: 1em;border-left: 5px solid #2282b2;font-size: 12pt;line-height: 1.4;color:#2282b2;} font-family:\"AmericanTypewriter\"}</style></head><body><h1>\(message.title!)</h1>\(message.content!)</body></html>" )
            .padding()

This was working great but after latests updates keep getting message 'Type 'WebView' does not conform to protocol 'UIViewRepresentable'

Please advice or give example how to use WKWebview in swiftUI latest version (iOS 15)

Upvotes: 0

Views: 2047

Answers (1)

this is an example of using WKWebview with your code:

struct Message {
    var title: String?
    var content: String?
}

struct ContentView: View {
    @State var message = Message(title: "The message title", content: "The message content")
    
    var body: some View {
        // -- note the default values for `message`
        HTMLView(htmlString: "<html<<head><style>body{font-size:36px;color:#2282b2;blockquote {margin: 0 auto;padding: 1em;border-left: 5px solid #2282b2;font-size: 12pt;line-height: 1.4;color:#2282b2;} font-family:\"AmericanTypewriter\"}</style></head><body><h1>\(message.title ?? "no title")</h1>\(message.content ?? "no content")</body></html>")
            .padding()
    }
}

On macos 12.4, using Xcode 13.3, targets ios-15 macCatalyst 12.3, tested on real devices only. Do not use forced unwrapping !.

Upvotes: 1

Related Questions