Download images from UIWebView

There is in my application UIWebView. There are some images on the loaded web page, and I would like to use these images elsewhere (e.g. display them in UIImageView)

So, is it possible to download images directly from UIWebViewwithout loading them again? Now I get the URLs of the images from the html file and load them, but this is too time consuming.

+4
source share
1 answer

I realized this: the key is to extract images from NSURLCache. However, since iOS 8, it seems you need to set the default cache as the first thing in application:didFinishLaunchingWithOptions:for this. For example:

IN application:didFinishLaunchingWithOptions:

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

Then after the download is complete UIWebView:

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 have one yet, you can get an array of images from UIWebViewusing

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

Source: https://habr.com/ru/post/1607764/


All Articles