0

I have a webview and would like to show an image in the webview (html)

  • My HTML :

    hello !img src="myimage.png" alt="myimage" height="42" width="42"!

(I used ! as tagend and tagstart, because I don't know how to add this here without be interpreted as HTML, even I pasted as code)

  • The myimage.png should be stored in app itself and not be loaded from a websource.

I don't know how to do that in a best practice way. Any help ?

UPDATE I tried with referenced Article, but still not succeeded: My Code for this:

        let path:NSString = NSBundle.mainBundle().bundlePath;
        var baseURL:NSURL=NSURL(fileURLWithPath: path as String)!;
        var htmlString:String! = texttemp
        myWebView.loadHTMLString(htmlString, baseURL: baseURL)

The same Image I can already load like the following -> works:

var image = UIImage(named: "myimage.png");
mcfly soft
  • 11,289
  • 26
  • 98
  • 202
  • Check this http://stackoverflow.com/questions/747407/using-html-and-local-images-within-uiwebview – Hamza Ansari Aug 01 '15 at 09:24
  • Thanks for helping. I see the concept, but practically it doesn't work. I updated the question with new code. Do you have any hint ? – mcfly soft Aug 01 '15 at 09:37

1 Answers1

1

Your updated code isn't right. You are creating a path to the bundle, not to the specific file. You need to use the NSBundle method pathForResource:ofType (or one of its variants) to build a path to your file. Then use that to create the URL.

The pathForResource:ofType family of methods return nil if the file can't be found, so you should check that you are getting back a path.

EDIT:

Looking at it more closely, I see that you are using the URL as the base URL for a call to loadHTMLString. This does look like a sound approach. What is your HTML string, and where is the image in your bundle?

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • my image is in the Images.xcassets file/bundle. I can see it in the list when clicking on it. As I wrote, I can access this file with "UIImage(named". The HTML String is the one I wrote and starts with "hello". When pasting the String with <> tags it was not shows in this thread, so I had to clasp the String with '!' – mcfly soft Aug 02 '15 at 06:30
  • Now it is working. I already tried this first, but I must have made a mistake. I use files outside of the bundle and did it as you described. (My first approach without a bundle). Thanks a lot. – mcfly soft Aug 02 '15 at 06:58