Reputation: 796
Well, i searched everywhere but i didn't have any luck with my situation. I am loading my webpage with UIWebView with the following code:
NSString *fullURL;
fullURL=@"http://domain.com";
NSURL *url=[NSURL URLWithString:fullURL];
NSURLRequest *requestObj=[NSURLRequest requestWithURL:url];
[_webView loadRequest:requestObj];
I want to load the remote HTML file but load the images from the bundle resourses. The HTML file looks like this:
<img src="http://domain.com/images/image.png" width="20px" height="20px"/>
Can this be done? The majority of the posts over the internet(and here) are for loading local HTML with local images/resources which is different in my case.
Any help with my code? Thanks
Upvotes: 1
Views: 1544
Reputation: 26
Had the exact same problem. Subclassing NSURLCache to redirect the cache to cache images from local storage worked like a charm.
Here is the writeup that I followed: http://www.cocoawithlove.com/2010/09/substituting-local-data-for-remote.html
Upvotes: 1
Reputation: 303
It would probably be better to use some more "loosely coupled" solution - not to edit the HTML code itself in some hacky way (regexp, not regexp... changing the HTML code manually is still pretty hacky).
As a matter of fact, I believe it can be done. The iOS just needs to be somehow informed that some of the assets are available offline, from the bundle.
Basically, when UIWebView is loading a page, first thing that happens behind the scene is downloading the main *.html page. Then all the graphics/css'es/js'es etc are being downloaded.
You can let the html file be downloaded "as is", but intercept those requests that are going to download graphics (+ other assets) and provide them from local bundle. Please refer to this post:
http://robnapier.net/blog/offline-uiwebview-nsurlprotocol-588
and apply appropriate changes. The big win here is that from the webview's (and code that loads / maintain via JavaScript calls it's content) perspective - nothing has changed at all. Only the custom NSURLProtocol itself knows that some data was loaded from local storage.
Upvotes: 1
Reputation: 6403
TL;DR Complicated, avoid if you can, but possible.
If you still want to do it: don't do a UIWebView :loadRequest
on the URL itself since it will trigger the start of downloading images very rapidly so modifying the images sources using Javascript will likely happen too late.
What you instead have would have to do is to download the contents of the URL on the native side and iterate the image tags there replacing the sources (quite complicated, don't use Regular Expressions to parse HTML btw, there are libraries for that), then injecting the modified HTML using UIWebView loadHTMLString:baseURL:
.
Upvotes: 0