Search code examples
swiftuiwkwebviewswift-playground

Double quotes in HTML in Swift Playgrounds WKWebView?


How do I use HTML that has double quotes("") in a Swift Playgrounds(iPad) WKWebView?

I tried to do it this way using \ before the quotes: Note, this was done in a playground not a app.

import UIKit
import WebKit
import PlaygroundSupport

let myURL = URL(string:"https://www.apple.com")

class WebViewController: UIViewController {
    override func loadView() {
        let config = WKWebViewConfiguration()
        let webView = WKWebView(frame: .zero, configuration: config)
        self.view = webView
    }
    
    var webView: WKWebView { self.view as! WKWebView }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.loadHTMLString("<iframe frameborder=\”0\” src=\”https://itch.io/embed/2292016\” width=\”552\” height=\”167\”><a href=\”https://v205.itch.io/ghost-battle\”>Ghost Battle by V205</a></iframe>", baseURL: nil)
    }
}

let vc = WebViewController()
PlaygroundPage.current.liveView = vc

But it gives a error: Invalid escape sequence in literal

Here is the HTML that I tried to use:

<iframe frameborder="0" src="https://itch.io/embed/2292016" width="552" height="167"><a href="https://v205.itch.io/ghost-battle">Ghost Battle by V205</a></iframe>

Thanks!


Solution

  • You can use the methods outlined here: How to print double quotes inside ""?

    For example, to use Extended String Delimiters, enclose your quoted string with the Number Sign #.

    Apart from Quotation Mark ", your string also contains the Right Double Quotation Mark , which needs to be replaced with ".

    Finally the line in your example becomes this:

    self.webView.loadHTMLString(#"<iframe frameborder="0" src="https://itch.io/embed/2292016" width="552" height="167"><a href="https://v205.itch.io/ghost-battle">Ghost Battle by V205</a></iframe>"#, baseURL: nil)