Remap UIWebView root URL to [[NSBundle mainBundle]

2019-06-28 00:45发布

问题:

I've got some HTML and some images in my iPhone app, arranged something like:

html/
    foo.html
images/
    bar.png

I can get bar.png to appear in my UIWebView a couple of different ways -- either loading foo.html from an NSUrl, and walking back up the directory tree from the html directory:

<img src="../images/bar.png"/>

or by loading foo.html into a string, using loadHtmlString, and using [[NSBundle mainBundle] bundleURL] as the baseURL:

<img src="images/bar.png"/>

Both of these are kind of clumsy, though -- in the first case, if I move HTML files around I have to rejigger all the relative paths, and in the second case, I have to ignore the actual path structure of the HTML files.

What I'd like to make work is this --

<img src="/images/bar.png"/>

-- treating the bundleURL as the root of the "site". Is there any way to make this work, or am I doomed to have that translated into file:///images/bar.png and have the file not found?

回答1:

If I'm not mistaken, you have some files in your project bundle that you want to load in your web view. You can do it simply with these few lines of code:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"bar" ofType:@"png"];
NSURL    *imageURL  = [NSURL fileURLWithPath:imagePath];

I'm assuming that you have a text/html file containing the pattern for your web view. You'll need to add the image as an object there (src="%@"...) and then add the imageURL to the pattern:

NSString *path = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"htmlPattern" ofType:@"html"]];
NSError *error;
NSString *pattern = [[NSString alloc]initWithContentsOfFile:path 
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];


htmlPage = [[NSString  alloc]initWithFormat:pattern,
            imageURL; 
webView = [[UIWebView alloc] initWithFrame:WEBVIEW_FRAME];
[webView loadHTMLString:htmlPage baseURL:[NSURL URLWithString:path]];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pattern]]];


回答2:

Only way I can see for you to do this would be to embed a web server in your app. Matt Gallagher has a blog post on this you could start from. Alternatively, CocoaHTTPServer and Mongoose could be dropped into your project.