2

I have an HTML file that is imported in my Xcode project with an image inside. The image is also inside my project folder but when I try to load the HTML file in the UIWebView the image is never loaded.

This is my HTML file:

<!DOCTYPE html>
<html>
<body>  
<img src="background.png"/>
</body>
</html>

And here is my Swift code to load the HTML file:

var htmlFile = NSBundle.mainBundle().pathForResource("Travel", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
weeb.loadHTMLString(htmlString!, baseURL: nil)

What is going wrong here? Thank you.

Rafail K.
  • 365
  • 3
  • 14
  • The first question i want to ask is why are you using an HTML page to show an image? Did you consider using `UIImageView`? – Harsh Aug 13 '16 at 08:47
  • I am using HMTL because I have to add a long text in my View with images. – Rafail K. Aug 13 '16 at 08:58

2 Answers2

3

I had the same issue. Here is my solution

create one folder for example html and put all html file along with your images and other resource. and then drag drop that html folder to your xcode project. xcode will ask you for copy at that time choose option "Create folder reference" and then finish, Check below screen shot.

enter image description here

So your folder structure look like this.

enter image description here

your html file will be

<!DOCTYPE html>
<html>
    <body>
        <img src="back.png"/>
    </body>
</html>

To load this html file your webview use the below code.

    let bundlePath = NSBundle.mainBundle().bundlePath
    let htmlFile = "\(bundlePath)/html/sample.html"

    let fileURL = NSURL(fileURLWithPath: htmlFile)
    webview.loadRequest(NSURLRequest(URL: fileURL))
Crazy Developer
  • 3,464
  • 3
  • 28
  • 62
1

I think you have the answer in the following post where the guy says

Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL

Using HTML and Local Images Within UIWebView

Community
  • 1
  • 1
Harsh
  • 2,852
  • 1
  • 13
  • 27
  • Thank you for your answer. I think that I have the same structure of code in swift with the related post and is not working. – Rafail K. Aug 13 '16 at 08:59