如何使用EGOCache更快地缓存和加载页面

时间:2014-01-20 19:32:21

标签: ios objective-c uiwebview nsdata nscache

我的iOS应用中有一个UIWebView根据之前的操作加载不同的网址。我希望这些页面尽可能快地加载。我找到了类EGOCachesource),我得到它将cacheData存储在library / Caches目录中。但我不知道如何检索此缓存以加快速度,我看不出差异。也许使用NSCache?我错过了什么?

- (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"];
        }
    }

谢谢!

2 个答案:

答案 0 :(得分:2)

好的,所以我制作了自己的方法,然后让它运转起来。您所要做的就是提供网址。看到这段代码:

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

答案 1 :(得分:0)

要完成您要实现的目标,您需要继承NSURLCache并实现所需的方法,并使用您的实现访问EGOCache。 UIWebView和NSURLConnection使用NSURLCache来缓存数据。实现自定义子类后,可以使用setSharedCache:将其实例设置为应用程序的URL缓存。