2011-07-14 60 views
15

我正在iOS上的圖像文字混合頁面上工作。我知道我可以使用UIWebView來實現目標。但問題是,用戶可能需要離線閱讀頁面。 對於文本部分,我可以將html保存到磁盤並在離線模式下加載它。 但是如何處理圖像?是否有可能將圖像緩存到磁盤並且UIWebView仍然可以顯示它們?如何緩存整個網頁與iOS中的圖像

謝謝!

回答

15

ASIHTTPRequest project有一個名爲ASIWebPageRequest的類,它被設計爲完全按照你的意願來做。如果您可以爲您的項目添加額外的依賴項,那麼我認爲這是一個很好的解決方案:ASIWebPageRequest

在我喜歡的網頁上面有如何使用一些很好的例子,但我會在這裏包括其中之一的完整性:

- (IBAction)loadURL:(NSURL *)url 
{ 
    // Assume request is a property of our controller 
    // First, we'll cancel any in-progress page load 
    [[self request] setDelegate:nil]; 
    [[self request] cancel]; 

    [self setRequest:[ASIWebPageRequest requestWithURL:url]]; 
    [[self request] setDelegate:self]; 
    [[self request] setDidFailSelector:@selector(webPageFetchFailed:)]; 
    [[self request] setDidFinishSelector:@selector(webPageFetchSucceeded:)]; 

    // Tell the request to embed external resources directly in the page 
    [[self request] setUrlReplacementMode:ASIReplaceExternalResourcesWithData]; 

    // It is strongly recommended you use a download cache with ASIWebPageRequest 
    // When using a cache, external resources are automatically stored in the cache 
    // and can be pulled from the cache on subsequent page loads 
    [[self request] setDownloadCache:[ASIDownloadCache sharedCache]]; 

    // Ask the download cache for a place to store the cached data 
    // This is the most efficient way for an ASIWebPageRequest to store a web page 
    [[self request] setDownloadDestinationPath: 
     [[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self request]]]; 

    [[self request] startAsynchronous]; 
} 

- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest 
{ 
    // Obviously you should handle the error properly... 
    NSLog(@"%@",[theRequest error]); 
} 

- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest 
{ 
    NSString *response = [NSString stringWithContentsOfFile: 
     [theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil]; 
    // Note we're setting the baseURL to the url of the page we downloaded. This is important! 
    [webView loadHTMLString:response baseURL:[request url]]; 
} 
+0

謝謝了這個樣本,將稍後再試。你能告訴我ASIReplaceExternalResourcesWithData如何嵌入數據到頁面嗎?該頁面仍然是緩存中的html文件,對嗎?請求是否修改了原始的HTML? –

+0

是的,你說得對。 ASI修改頁面並用[數據URI](http://en.wikipedia.org/wiki/Data_URI_scheme)替換這些資源。或者,您可以使用稱爲「ASIReplaceExternalResourcesWithLocalURLs」的不同URL替換模式,該模式會將資源下載爲文件,但仍會修改HTML以指向這些本地文件。 – xoebus

+0

謝謝xoebus。我還發現要啓用脫機瀏覽,我需要添加以下代碼行:'request.cachePolicy = ASIAskServerIfModifiedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy;' –