In iOS, given a web page loaded inside a WKWebView
, how can I show my own UIImage
inside the HTML?
Thanks
UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];
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.
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.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With