在我的应用程序中有一个 UIWebView
。其中加载的网页有一些图像,我想在其他地方使用这些图像(例如在 UIImageView
中显示它们)
那么是否可以直接从UIWebView
获取加载好的图片而不需要再次下载呢?我现在正在做的是从 html 文件中获取图像的 URL 并下载它们,但这太耗时了。
最佳答案
我已经弄明白了:关键是从 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:@","];
关于ios - 从 UIWebView 获取加载的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624106/