Anthony Mattox
Anthony Mattox

Reputation: 7118

UIWebView link to local files without setting the baseURL to the app directory

I have a web view in an app loading an html snippet from a server which includes text and images. I'm wrapping that in a little html and putting it into a web view like this:

NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"style" ofType:@"css"];

NSString *cssLink = [NSString stringWithFormat:@"<link href='file://%@/' type='text/css' rel='stylesheet'/>", cssPath];

NSString *html = [[NSString stringWithFormat:@"<html><head><title></title><meta charset='UTF-8' />%@</head><body>%@</body></html>", cssLink, htmlContent] retain];

[myWebView loadHTMLString:html baseURL:currentURL];

Is there any way to fix the above code so that the link to the local stylesheet works?

I could load the stylesheet without problem if I change the base url to the local application resources file, but this breaks the image links within the html loaded from the server.

I could also include the contents of the stylesheet directly into the html, but would prefer not to do that for a number of reasons.

Thanks.

Upvotes: 6

Views: 3960

Answers (2)

Jonathan Zhan
Jonathan Zhan

Reputation: 1893

Probably too late to help you, Anthony. Sorry! Here's a working solution for any other brave heroes walking the same path:

NSString* bundlePath = [[[NSBundle mainBundle] bundleURL] absoluteString];

NSString* cssString = [NSString stringWithFormat:@"<html><head><base href='%@'><link rel='stylesheet' type='text/css' href='style.css'/></head><body>Hi Mom!</body></html>"
                      , bundlePath"];

Upvotes: 2

William Niu
William Niu

Reputation: 15853

What is currentURL? It should be [[NSBundle mainBundle] bundleURL], e.g.

[webview loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];

And I believe the cssPath can be just the filename, instead of the absolute path.

Upvotes: 2

Related Questions