2

I have this this code:

NSURL *mainBundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:htmlFile baseURL:mainBundleURL];

I know the htmlFile is correct. It has inside:

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

I also know the stylesheet.css in in the mainBundle. I checked the project.app contents.

Problem is that is the webview is empty. But if I use base Url as nil:

[webView loadHTMLString:htmlFile baseURL:nil];

The webview shows the content, but without the css file.

I have no idea why this is not working. Thanks in advance.

3
  • BTW i´m trying in ios 6.1 Commented Oct 2, 2013 at 10:21
  • Why not load the html from an NSURLRequest? Commented Oct 2, 2013 at 11:22
  • I only have the html file in a string. Commented Oct 3, 2013 at 14:07

3 Answers 3

3

I solved this using the resourceURL property

NSURL *baseURL = [[NSBundle mainBundle] resourceURL];

and then [webView loadHTMLString:htmlFile baseURL:baseURL];

-Sal

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

Comments

1

Most examples reference baseUrl: nil but in order to access the CSS file you need to reference the bundle so that the <link rel="stylesheet" ... can access the file.

This is my solution in Swift 3:

let baseUrl : URL = Bundle.main.resourceURL! as URL
let htmlFile = Bundle.main.path(forResource: "*html file name*", ofType: "html")
let htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(htmlString!, baseURL: baseUrl) 

Credit the Sal's answer for pointing this out.

Comments

0

Perhabs shouldStartLoadWithRequest method blocks your request. Try this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.absoluteString hasPrefix:@"file"]) {return YES;}

    //deal with the request
}

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.