UIWebView refers to local files without setting baseURL in the application directory

I have a web view in an application that downloads an html fragment from a server that includes text and images. I wrap this in a small html and put it in a web view as follows:

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 a way to fix the above code so that the link to the local stylesheet works?

I can load the stylesheet without problems if I change the base url to the local application resource file, but this will break the links to images inside the html downloaded from the server.

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

Thanks.

+6
source share
2 answers

What is currentURL ? It should be [[NSBundle mainBundle] bundleURL] , for example

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

And I believe that cssPath may just be a file name, not an absolute path.

+2
source

Perhaps too late to help you, Anthony. Sorry Here's a working solution for any other brave heroes following 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"]; 
+2
source

Source: https://habr.com/ru/post/900851/


All Articles