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.
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With