2014-01-20 59 views
0

我有一個UIWebView在我的iOS應用程序加載不同的網址取決於以前的行動。我不想讓這些頁面儘快加載。我發現類EGOCachesource),我的工作是將cacheData存儲在庫/ Caches目錄中。但我不知道如何檢索這個緩存來加載它,我看不出有什麼不同。也許使用NSCache?我錯過了什麼?如何使用EGOCache緩存和加載頁面更快

- (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

好吧,我做了我自己的方法,我得到了它的工作。你所要做的就是給出url地址。看到這個代碼:

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

要實現您正在嘗試實現的目標,您需要子類NSURLCache並實現所需的方法,並使用您的實現訪問EGOCache。 UIWebView和NSURLConnection使用NSURLCache來緩存數據。一旦實現了自定義子類,就可以使用setSharedCache:將其實例設置爲應用程序的URL緩存。

+0

你有任何代碼或教程,你可以告訴我嗎?我是一個新手抱歉... – Tibbe