从 UIWebView 获取加载的图像 [英] Get loaded images from UIWebView

查看:25
本文介绍了从 UIWebView 获取加载的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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.

推荐答案

我明白了这一点:关键是从 NSURLCache 中提取图像.但是,从 iOS 8 开始,您似乎需要在 application:didFinishLaunchingWithOptions: 中将默认缓存设置为第一件事才能使其工作.例如:

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:

application:didFinishLaunchingWithOptions:

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

然后在您的 UIWebView 加载完成后:

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:@","];

这篇关于从 UIWebView 获取加载的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆