appzYourLife appzYourLife - 4 months ago 59
iOS Question

WKWebView: insert UIImage into web page

In iOS, given a web page loaded inside a

WKWebView
, how can I show my own
UIImage
inside the HTML?

Thanks

Answer

One way to do it is using Base64 encoding. The following should be a completely working example, assuming you wire up a UIWebView and have an image of the correct name:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if let image = UIImage(named: "Castle"),
            let data = UIImagePNGRepresentation(image) {
            let base64 = data.base64EncodedString(options: [])
            let url = "data:application/png;base64," + base64
            let html = "<html><head></head><body><h1>Hello World!</h1><img src='\(url)'></body></html>"
            webView.loadHTMLString(html, baseURL: URL(fileURLWithPath: ""))
        }

    }

}

I tried to do this in Playground, but couldn't get the webView to display, so it's a minimal app...

Output:

enter image description here

Comments