Get loaded images from UIWebView

老子叫甜甜 提交于 2019-12-10 17:31:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!