【问题标题】:Get loaded images from UIWebView从 UIWebView 获取加载的图像
【发布时间】:2015-12-13 22:55:48
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c swift uiwebview uiimage


    【解决方案1】:

    我想通了:关键是从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:@","];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2012-08-19
      相关资源
      最近更新 更多