2015-09-17 64 views
4

在我的应用程序中有一个UIWebView。其中加载的网页有一些图像,我想在其他地方使用这些图像(例如,在UIImageView中显示它们)从UIWebView获取加载的图像

那么,是否可以直接从UIWebView获取加载的图像,而无需再次下载它们?我现在正在做的是从html文件获取图像的URL并下载它们,但这太费时了。

回答

0

我已经想通了:关键是从NSURLCache中提取图像。但是,从iOS 8开始,似乎您需要将默认缓存设置为application:didFinishLaunchingWithOptions:中的第一项,才能使其工作。例如:

application:didFinishLaunchingWithOptions:

[NSURLCache setSharedURLCache:[[NSURLCache alloc] 
    initWithMemoryCapacity:32*1024*1024 diskCapacity:64*1024*1024 diskPath:...] 

那么你UIWebView加载完成后:

NSCachedURLResponse * response = [[NSURLCache sharedURLCache] 
    cachedResponseForRequest:[NSURLRequest requestWithURL: 
     [NSURL URLWithString:@"http://.../image.png"]]]; 
if (response.data) 
{ 
    UIImage * nativeImage = [UIImage imageWithData:response.data]; 
    .... 
} 

如果你不已经拥有了它,你可以从UIWebView获取图像阵列与

NSArray * images = [[webView stringByEvaluatingJavaScriptFromString: 
    @"var imgs = []; for (var i = 0; i < document.images.length; i++) " 
     "imgs.push(document.images[i].src); imgs.toString();"] 
    componentsSeparatedByString:@","];