Search code examples
iosobjective-cuiwebviewnsdatanscache

How to use EGOCache to cache and load page faster


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!


Solution

  • 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];
    }