5

In iOS, given a web page loaded inside a WKWebView, how can I show my own UIImage inside the HTML?

Thanks

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • javascript is the only way, write a script to find image and repleace it – Lu_ Aug 03 '16 at 12:40
  • I have a `UIImage` in memory, what URL should I write with JavaScript? – Luca Angeletti Aug 03 '16 at 12:42
  • Define "in memory". – Larme Aug 03 '16 at 12:48
  • I mean a `UIImage` object I created programmatically. Something like `let image: UIImage = ...` – Luca Angeletti Aug 03 '16 at 12:49
  • Just put it above. – Cy-4AH Aug 03 '16 at 12:52
  • 1
    Try to save your UIImage to /Library or /Documents folder of your application by converting to NSData with `UIImagePNGRepresentation(yourImage)`. Then use the absolute path to put into the image element in your html page. Btw, I'm not sure that absolute path works, maybe you have to use relative path. – Duyen-Hoa Aug 03 '16 at 12:53
  • Thanks _@Hoa_ I'm trying. It's a very useful comment. – Luca Angeletti Aug 03 '16 at 12:54
  • 2
    If it does not work, you can try with base64 string for image. https://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support – Duyen-Hoa Aug 03 '16 at 13:03
  • 1
    I have successfully done this using a similar technique to @Hoa's 2nd one - use base64 then embed a "data:application/pdf;base64,..." URL in your HTML. See http://stackoverflow.com/questions/11251340/convert-between-uiimage-and-base64-string – Grimxn Aug 03 '16 at 14:19

1 Answers1

12

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

Grimxn
  • 22,115
  • 10
  • 72
  • 85