1

I have added my Html, CSS and image files in the bundle of my Xcode application.

In my project I loaded the Html content in the UIWebView like this,

NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"html" inDirectory:nil];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];

NSURL *Url = [NSURL fileURLWithPath:htmlString];
[self.webView loadHTMLString:htmlString baseURL:Url];

The Html file is loaded, but CSS and Images are missing.

In my Html file add the CSS and images as follows,

<link href="/css/myCss.css" type="text/css" rel="stylesheet"/>

   <img class"icon" alt="" src="/img/icon.png" />

Need help to resolve this problem.

5
  • try adding tow dots before first '/' in addresses eg. "../css/myCss.css" . Commented Jul 28, 2014 at 7:29
  • @AbhinavGauniyal: Just tried. But not working Commented Jul 28, 2014 at 7:31
  • Does it work if you remove the folders in the paths? So that /css/myCss.css becomes myCss.css and /img/icon.png becomes icon.png. I believe that's how i got it to work in my app a while ago, despite the fact that the files were in folders & groups. Commented Jul 28, 2014 at 8:01
  • I have tried that too, but result is same Commented Jul 28, 2014 at 8:02
  • Oh, sorry, just checked the code, and the app i was thinking about didn't even use an WebView :/ Commented Jul 28, 2014 at 8:17

1 Answer 1

1

First, get rid of the initial / in the file paths in the html so you have:

<link href="css/myCss.css" type="text/css" rel="stylesheet"/>

<img class"icon" alt="" src="img/icon.png" />

Make sure when you are adding the files you are using the Folders option: "Create folder references for any added folders".

The code loading the html in the webview can be simplified to look like:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"html" inDirectory:nil];

[self.webView loadRequest:[NSURLRequest requestWithURL:url]];

I also suggest putting your html assets into a "www" or "html" folder instead of the base folder.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.