从UIWebView获取加载的图像

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

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

我已经想通了:关键是从NSURLCache提取图像。 但是,从iOS 8开始,似乎需要将默认caching设置为application:didFinishLaunchingWithOptions:的第一件事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:@","];