Redirect UIWebView URL to [[NSBundle mainBundle] bundleURL]

I have HTML and some images in the application for iPhone, sorted something like this:

html/ foo.html images/ bar.png 

I can get bar.png in my UIWebView couple of different ways: either load foo.html from NSUrl , or return to 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 baseURL :

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

Both of these kinds are inconvenient, although in the first case, if I move the HTML files around, I have to redraw all the relative paths, and in the second case I have to ignore the actual path structure of the HTML files.

What I would like to do is

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

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

+4
source share
2 answers

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

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

I assume that you have a text / html file containing a template for your web view. You need to add the image as an object ( src="%@"... ), and then add imageURL to the template:

 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]]]; 
0
source

The only way I see for you is to embed a web server in your application. Matt Gallagher has a blog post about this from which you can start. Alternatively, CocoaHTTPServer and Mongoose can be dropped into your project.

+1
source

All Articles