美文网首页iOS开发收藏ios
WKWebView加载本地图片的几种方案

WKWebView加载本地图片的几种方案

作者: 秋意阑珊 | 来源:发表于2020-03-22 23:36 被阅读0次

前言

官方通知

UIWebview即将不再可用,Apple开发者网站的新闻及更新页面,2019年12月23日,已经更新了UIWebview废弃的最后通知,这次是必须适用wkwebview了。

webview跨域访问安全漏洞

UIWebview可以加载本地图片,但是其实这是个跨域访问安全漏洞,还挺严重的,大家可以了解一下。

WKWebview更加安全,默认allowFileAccessFromFileURLs是关闭的,导致一些需求场景下网页中需要加载本地图片资源的时候是无法直接加载的,我在这方面也遇到了一些问题,所以整理了一下搜到的常见的解决办法,都一一验证了下,整合了一个demo,希望能帮到大家。
demo中有所有方案的演示代码,代码地址WKWebviewLoadLocalImages,如果觉得有用的话,可以点个star,谢谢。

WKWebview加载本地图片4种方案:

方案1、资源放到沙盒tmp临时文件夹下

loadHTMLString:baseURL方法加载html文本(html中有沙盒文件路径),图片需要存储到沙盒tmp目录下,baseURL参数传入本地文件路径的url,或者设置“file://”,图片文件可以正常加载。
其他沙盒目录(Cache、Library)即便在baseURL中进行配置依然不能加载本地图片。
方案1演示代码

方案2、设置自定义的URLScheme

使用系统方法(iOS11之后的新方法)设置自定义url scheme,然后在代理方法中处理本地图片的加载

// 系统方法,iOS11以后系统可用
- (void)setURLSchemeHandler:(nullable id <WKURLSchemeHandler>)urlSchemeHandler forURLScheme:(NSString *)urlScheme API_AVAILABLE(macos(10.13), ios(11.0));】

1、在WKWebViewConfiguration中设置自己自定义的urlScheme

#define MyLocalImageScheme @"localimages"



- (WKWebView *)webView {
    if (_webView == nil) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        if (@available(iOS 11.0, *)) {
            [configuration setURLSchemeHandler:self forURLScheme:MyLocalImageScheme];
        } else {
            // Fallback on earlier versions
        }
        _webView = [[WKWebView alloc] initWithFrame:[self.view frame] configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    
    return _webView;
}

2、把html中img标签对应的src中的对应本的file url的scheme改成自定义的,然后加载html

NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"index2" withExtension:@"html"];
    
NSString *html = [[NSString alloc] initWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *imageurlArray = [html imageURLs];//抓取html中所有img标签中的图片url

NSString *imageUrl = [imageurlArray firstObject];
self.localPath = [self localPathForImageUrl:imageUrl];
NSURL *localPathURL = [NSURL fileURLWithPath:self.localPath];
// 修改scheme为自定义scheme
localPathURL = [localPathURL changeURLScheme:MyLocalImageScheme];
// html中imageurl替换成本地地址
html = [html stringByReplacingOccurrencesOfString:imageUrl withString:localPathURL.absoluteString];

、、、

 // 加载html
 [self.webView loadHTMLString:html baseURL:nil];

3、代理方法中处理自定义协议的本地图片的加载

把地址替换回本地图片scheme:file,然后异步加载本地图片,并把结果回传给webview

NSURL *requestURL = urlSchemeTask.request.URL;
    NSString *filter = [NSString stringWithFormat:MyLocalImageScheme];

    if (![requestURL.absoluteString containsString:filter]) {
        return;
    }

    // scheme切换回本地文件协议file://
    NSURL *fileURL = [requestURL changeURLScheme:@"file"];
    NSURLRequest *fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:0];
    
    // 异步加载本地图片
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:fileUrlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       NSURLResponse *response2 = [[NSURLResponse alloc] initWithURL:urlSchemeTask.request.URL MIMEType:response.MIMEType expectedContentLength:data.length textEncodingName:nil];
       if (error) {
           [urlSchemeTask didFailWithError:error];
       } else {// 回传结果给webview
           [urlSchemeTask didReceiveResponse:response2];
           [urlSchemeTask didReceiveData:data];
           [urlSchemeTask didFinish];
       }
    }];

    [dataTask resume];
}

- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask  API_AVAILABLE(ios(11.0)) {

}

这样就ok了,网页中的本地图片图片能正常展示了

方案3、直接把图片数据转成base64格式,转换后的数据替换到src中

    NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"index3" withExtension:@"html"];
    
    __block NSString *html = [[NSString alloc] initWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
    NSArray *imageurlArray = [html imageURLs];
    
    NSString *imageUrl = [imageurlArray firstObject];
    // 下载图片
    [ImageDownloader downloadImageWithURL:[NSURL URLWithString:imageUrl] completionHandler:^(NSData * _Nonnull data, NSError * _Nonnull error) {
        UIImage *image = [UIImage imageWithData:data];
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
       
        NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@", [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
                                                   
        // url替换成本图片base64数据
        html = [html stringByReplacingOccurrencesOfString:imageUrl withString:imageSource];
       
        dispatch_async(dispatch_get_main_queue(), ^{
            // 加载html文件
            [self.webView loadHTMLString:html baseURL:nil];
        });
    }];

方案4、把html文件和图片资源放到沙盒同一个目录下

把html文件和图片资源放到沙盒同一个目录下,html中的本地图片可以正常加载,而且不限定沙盒目录,放在Cache、tmp中都可以正常加载。

    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"index4" withExtension:@"html"];
    
    NSString *html = [[NSString alloc] initWithContentsOfURL:bundlePath encoding:NSUTF8StringEncoding error:nil];
    NSArray *imageurlArray = [html imageURLs];
    NSString *imageUrl = [imageurlArray firstObject];
        
    // cache
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *imagePath = [docPath stringByAppendingPathComponent:[imageUrl md5]];
    NSURL *imagePathURL = [NSURL fileURLWithPath:imagePath];
    // 替换成沙盒路径:file:///****
    html = [html stringByReplacingOccurrencesOfString:imageUrl withString:imagePathURL.absoluteString];

    // html保存到跟图片同一目录下
    NSError *error;
    NSString *htmlPath = [[docPath stringByAppendingPathComponent:@"index4"] stringByAppendingPathExtension:@"html"];
    NSLog(@"写入的HTML:%@", html);
    
    [html writeToFile:htmlPath atomically:NO encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"html写入失败");
    } else {
        NSLog(@"html写入成功");
    }
    
    // 异步下载图片
    [ImageDownloader downloadImageWithURL:[NSURL URLWithString:imageUrl] completionHandler:^(NSData * _Nonnull data, NSError * _Nonnull error) {
        // 写入沙盒
        if (![data writeToFile:imagePath atomically:NO]) {
           NSLog(@"图片写入本地失败:%@\n", imagePath);
        } else {
            NSLog(@"图片写入本地成功:%@\n", imagePath);
        }
        
        NSURL *localFileURL = [NSURL fileURLWithPath:htmlPath];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 下面两种方式都可以正常加载图片
            // loadRequest可以正常加载
//            [self.webView loadRequest:[NSURLRequest requestWithURL:localFileURL]];
            
            /*
             下面这种方式必须指定准确的文件地址或者图片文件所在的目录才能正常加载
             */
            [self.webView loadFileURL:localFileURL allowingReadAccessToURL:[localFileURL URLByDeletingLastPathComponent]];
        });
    }];

总结

上面列出的各种方法,只是把各种方案都的核心情况验证了一下,写出的demo。在实际的项目中需要考虑html加载本地资源的具体情况,图片本地缓存需要判断缓存是否命中防止重复加载,多张图片要考虑图片的异步加载和刷新webview的实际,可能还有一些特殊情况可能没有考虑到的,大家可以留言给我,我再补上。
最后再贴一下完整demo的地址:WKWebviewLoadLocalImages,觉得有用的可以star一下。

相关文章

  • WKWebView加载本地图片的几种方案

    前言 官方通知 UIWebview即将不再可用,Apple开发者网站的新闻及更新页面,2019年12月23日,已经...

  • (WKWebView) - 禁止长按交互

    使用WKWebView展示html文章,loadFileURL加载html文件,加载本地缓存图片。长按图片会弹窗,...

  • React Native组件学习之Image

    Demo展示 上面是去加载网络图片,下面是加载本地图片 加载图片的几种方式 加载本地图片从项目中加载图片(一般是会...

  • WKWebView长按图片点击保存闪退问题的解决方案 WKWebView默认加载的页面图片长按都会触发保存图片的操...

  • flutter 图片

    加载网络图片网络图片 加载本地图片效果 实现图片圆角的几种方式 CircleAvatarCircleAvatar ...

  • 2019-03-22

    iOS WKWebView 远端h5优先加载本地资源 前言:UIWebView调用远端h5页面,优先加载本地图片、...

  • 解决WKWebView不显示H5中引用的Library本地图片问

    问题:由UIWebView切WKWebView后,HTML加载本地HTMLString时,图片无法显示。 WKWe...

  • WF: _WebFilterIsActive returning

    在使用WKWebView的加载本地文件的时候图片资源不显示,并且log日志为:WF: _WebFilterIsAc...

  • WKWebView缓存和缓存刷新

    实现:1、WKWebView加载过内容需要做本地存储。2、WKWebView加载的url本地有缓存时,在无网状态下...

  • iOS WKWebView加载pdf巨坑

    WKWebView加载pdf不管是本地加载还是网络加载,再push到另外一个页面,返回到wkwebView页面,原...

网友评论

    本文标题:WKWebView加载本地图片的几种方案

    本文链接:https://www.haomeiwen.com/subject/ompbyhtx.html