Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 871
Luca Angeletti Avatar asked Aug 03 '16 12:08

Luca Angeletti


People also ask

How do you add a UIImage in Objective C?

UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];

Is WKWebView deprecated?

Since then, we've recommended that you adopt WKWebView instead of UIWebView and WebView — both of which were formally deprecated. New apps containing these frameworks are no longer accepted by the App Store.

Is WKWebView the same as Safari?

WKWebView - This view allows developers to embed web content in your app. You can think of WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView has the benefit of the Nitro JavaScript engine and offers more features.

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


1 Answers

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

like image 169
Grimxn Avatar answered Sep 20 '22 19:09

Grimxn