Reputation: 417
I have an UIWebView
in my iOS app that loads different url's depending on a previous action. I wan't these pages to load as fast as possible. I found the class EGOCache
(source) and I i got it working to store cacheData in library/Caches directory. But I'm not sure how to retrieve this cache to load it faster, I can't see the difference. Maybe use NSCache? What have I missed?
- (void)webViewDidStartLoad:(UIWebView *)webView {
if (webView_1) {
NSString *urlAddress = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 10.0];
[webView1 loadRequest:request];
NSData *data0 = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
[[EGOCache globalCache] setData:data0 forKey:@"webCache"];
}
}
Thanks!
Upvotes: 2
Views: 1712
Reputation: 417
Okay so I made my own method and I got it working. All you have to do is to give the url address. See this code:
-(void)loadPage:(NSString *)urlAddress {
NSURL *url = [NSURL URLWithString:urlAddress];
NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [cachePath stringByAppendingPathComponent:@"/xxx.APPNAME/EGOCache/EGOCache.plist"];
NSDictionary *dict =[NSDictionary dictionaryWithContentsOfFile:file];
if ([dict objectForKey:urlAddress] )
{
NSData *data = [[EGOCache globalCache] dataForKey:urlAddress];
data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
NSLog(@"loading from cache %@",urlAddress);
}else{
NSData *data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
[[EGOCache globalCache] setData:data forKey:urlAddress];
NSLog(@"saving cache %@",urlAddress);
[[EGOCache globalCache] setDefaultTimeoutInterval:60*60*24*4]; //timeout (4 days)
}
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 10.0];
[webView loadRequest:request];
}
Upvotes: 3
Reputation: 21254
To accomplish what you are trying to implement you would need to subclass NSURLCache and implement the required methods, with your implementation accessing EGOCache. UIWebView and NSURLConnection use NSURLCache for caching data. Once you have your custom subclass implemented, you would set an instance of it to be your application's URL cache using setSharedCache:
.
Upvotes: 0