2013-05-18 59 views
1

我通過NSURLProtocol(這意味着圖像幾乎立即返回)提供本地圖像到我的UIWebView,但我遇到了緩存圖像(第一次加載後再次顯示圖像)的問題加載時間更長。我的NSURLProtocol中是否有這樣的東西?UIWebView中的緩存圖片需要更長時間才能加載? (NSURLProtocol?)

@implementation URLProtocol 

+ (BOOL) canInitWithRequest:(NSURLRequest *)request { 
    return [request.URL.scheme isEqualToString:@"file"] || 
      [request.URL.scheme isEqualToString:@"http"]; 
} 

+ (NSURLRequest*) canonicalRequestForRequest:(NSURLRequest *)request { 
    return request; 
} 

- (void) startLoading { 
    id<NSURLProtocolClient> client = self.client; 
    NSURLRequest* request = self.request; 
    NSString *fileToLoad = request.URL.absoluteString; 
    NSURLResponse *response; 

    if([fileToLoad hasPrefix:@"http://app-fullpath/"]){ 
     fileToLoad = [fileToLoad stringByReplacingOccurrencesOfString:@"http://app-fullpath/" withString:@""]; 
    } else { 
     fileToLoad = [[NSURL URLWithString:fileToLoad] path]; 
    } 

    NSData* data = [NSData dataWithContentsOfFile:fileToLoad]; 

    response = [[NSHTTPURLResponse alloc] initWithURL:[request URL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:[NSDictionary dictionary]]; 

    [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 
    [client URLProtocol:self didLoadData:data]; 
    [client URLProtocolDidFinishLoading:self]; 
} 

- (void) stopLoading { } 
@end 

任何速度建議,javascript/html或iOS?

+0

你爲什麼要加載本地圖像到UIWebView? – danypata

+1

有許多用途,比如HTML應用程序,以及UIWebView比UITextView更容易操作的事實。這對我來說是最好的選擇。 – mattsven

+0

另一個用例是加載本地化圖像。您可以請求本地png,在運行時檢查當前的語言環境並加載不同的映像。您也可以通過加載替代CSS來將其用於動態主題化,而無需更改HTML中的路徑。 –

回答

1

我的問題是,UIWebView給文本一個比圖像更高的優先級,所以文本先佈局,然後處理圖像。爲了解決這個問題,我創建了一個DOM表示形式的HTML &圖像,然後我將所有圖像替換爲通過JavaScript加載的圖像(new Image()),並立即顯示。

+0

你能告訴我你是怎麼做到的嗎? – Vijay

+0

@Vijay我不推薦這種解決方案,因爲它效率低下,並沒有解決所有情況。如果您遇到此問題,請嘗試刪除緩存。 – mattsven

+0

感謝您的回覆。我想從HTML加載圖像。請看看這個問題:http://stackoverflow.com/questions/35863295/ios-9-0-uiwebview-behaviour-on-wifi – Vijay

相關問題