Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uiwebview

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.

like image 216
Anthony Mattox Avatar asked Nov 05 '11 18:11

Anthony Mattox


2 Answers

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.

like image 128
William Niu Avatar answered Oct 15 '22 06:10

William Niu


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"];
like image 41
Jonathan Zhan Avatar answered Oct 15 '22 05:10

Jonathan Zhan