问题
In my app there's a UIWebView. The loaded webpage in it has some images, and I would like to use these images in somewhere else (e.g. display them in UIImageView)
So is it possible to get the loaded images directly from UIWebView without downloading them again? What I am doing now is get the URLs to the images from the html file and download them, but this is too time consuming.
回答1:
I've figured this out: the key is to extract the images from the NSURLCache. However, since iOS 8, it seems you need to set the default cache as the first thing in application:didFinishLaunchingWithOptions: for this to work. For example:
In application:didFinishLaunchingWithOptions:
[NSURLCache setSharedURLCache:[[NSURLCache alloc]
initWithMemoryCapacity:32*1024*1024 diskCapacity:64*1024*1024 diskPath:...]
Then after your UIWebView has finished loading:
NSCachedURLResponse * response = [[NSURLCache sharedURLCache]
cachedResponseForRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://.../image.png"]]];
if (response.data)
{
UIImage * nativeImage = [UIImage imageWithData:response.data];
....
}
If you don't already have it, you can get an array of images from the UIWebView with
NSArray * images = [[webView stringByEvaluatingJavaScriptFromString:
@"var imgs = []; for (var i = 0; i < document.images.length; i++) "
"imgs.push(document.images[i].src); imgs.toString();"]
componentsSeparatedByString:@","];
来源:https://stackoverflow.com/questions/32624106/get-loaded-images-from-uiwebview