13
votes

I've been testing an iPhone view controller that uses a UIWebView to load external content, as opposed to resources in the project's bundle. Another engineer noticed that the web view wasn't caching at all, so I went into do some research. Some older questions indicated that UIWebView's just couldn't cache external content.

Previous SO Questions on UIWebView caching:

Those posts were pretty deflating, but I noticed that they were all asked before iOS 4.0 came out. I tested the following approach for caching, which seemed pretty straight-forward.

NSURLRequest *request = [NSURLRequest requestWithURL:myUrl 
      cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
[webView loadRequest:request];

This seems to work great on iOS 4.3 but doesn't work at all on iOS 3.0. I tested this by pointing the devices to a Charles proxy (on iPhone, Settings -> WiFi, Manual proxy) and recording the traffic to my server.

Did the UIWebView start observing the cache policy in iOS 4.0? Can anyone else confirm this or am I just imagining things?

3
I tested on iOS 4.0 with no cache policy, just [NSURLRequest requestWithURL:myUrl] and it seemed to load from the cachegoldierox
I think this link will help you... stackoverflow.com/questions/2352841/…junaidsidhu

3 Answers

3
votes

Yes, in iOS 4.0 the cache started working.

There is a class in Foundation framework that's in charge of handling this, it's NSCache. It's been in Mac OS X from ages but it wasn't implemented in iOS until iOS 4.0. Even then it was implemented only partially: it didn't support disk caching but only memory caching (so the cache was very unreliable due to memory being released when requested by the system).

NSCache received an update in iOS 5.0 that added support for disk caching and it now works like the Mac version and can be used with no problem.

-1
votes

I just checked NSURLRequest.h

Most of the code in iOS SDK, which has a versioning assertion has a if statement, something like this:

#if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED

But the method

- (id)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;

doesn't seem to have any such thing, thus I would guess it has been there forever.

-2
votes
NSURLCache* theCache = [NSURLCache sharedURLCache];
[theCache setMemoryCapacity:4 * 1024 * 1024];
[theCache setDiskCapacity:512*1024];

[NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];