2013-05-18 36 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

相关问题