1
votes

As part of iOS9 we have the new method loadData() introduced into WKWebView.

I have NSData object that is output of UIImageJPEGRepresentation that I want to render in a WKWebView. Prior to iOS9, in order to render image in wkwebview, I was:

  • storing nsdata on the local file system as a .jpeg file
  • create a nsurl with fileWithUrl init method
  • Call wkwebview.loadRequest(url) where url is the nsurl created in previous step

I was hoping take advantage of the new iOS9 method where I can directly call the wkwebview.loadData(nsdata, MIMEType:"image", characterEncoding:"ASCII", baseURL: NSURL("random"))

I am not able to render the image using the above loadData call. Could be issue with the params I am passing for MIMEType, characterEncoding and baseUrl. Could not find any examples for this method call anywhere.

Notes:

  • I am not sure what characterEncoding to use when rendering image
  • The baseUrl cannot be nil and so initialized it to a random url
2

2 Answers

0
votes

This might be a late answer, we had similar issue in one of our projects, one way you can solve this is using html's power by embedding the content inside html.

func loadDataContent(data:Data,mimeType:String) {
    let urlStr = "<iframe width=\"100%\" height=\"100%\" src=\"data:\(mimeType);base64,\(data.base64EncodedString())\"></iframe>"
    webBrowser?.loadHTMLString(urlStr, baseURL: nil)
}
-1
votes

This works for me:

    if let path = NSBundle.mainBundle().pathForResource("Test", ofType: "jpg") {
        if let data = NSData(contentsOfFile: path) {
            webView.loadData(data, MIMEType: "image/jpeg",
                characterEncodingName: "", baseURL: NSURL(string: "")!)
        }
    }

The characterEncodingName and baseURL look a bit odd but I doubt they are relevant for loading image/jpeg type data.