Asset Catalog images inside a UIWebView

753 Views Asked by At

Xcode 9 has taken another step forward with vectors inside of iOS projects. It will apparently retain the source PDF so that images may be generated as needed with full quality.

I'm wondering if it's yet possible to access these images from the HTML inside of a UIWebView?

I can imagine three possible ways of doing this:

  1. Some magic that you place within your HTML or CSS that iOS will recognize and replace. For example:

    <img src={{Asset Name}}>

  2. Knowing the naming scheme to get at the asset. For example:

    <img src="some/path/asset~ipad@3x">

  3. "Render" the image outside the UIWebView and pass it in.

Are any of these possible? Is there another way?

Given how far we've come with vectors, I'd hate to have to pre-render every image variation and package them outside the asset catalog if I don't have to.

1

There are 1 best solutions below

0
On

Today i needed to render the UIImage from XCAsset's into an UIWebView.

My requirement was to prepare the appropriate HTML and load it into the UIWebView as follows

self.myWebView.loadHTMLString(html, baseURL: nil)

In order to load images from XCAsset's, first loaded the image into an UIImage, then convert it back to Base64 Encoding, then put the image into the <img> tag.

The code looks like following

let redClockImage = UIImage.init(named: "clock-red")!
let imageData:Data =  UIImagePNGRepresentation(self)!
let base64String = imageData.base64EncodedString()

let html = """
           //my html
           <img src="data:image/png;base64, \(base64String)" />
           //rest of my html
           """

//then i load this html into the webview
self.myWebView.loadHTMLString(html, baseURL: nil)

For Convenience i moved the UIImage -> Base64 String conversion into an extension.