WKWebView加載本地圖片的幾種方案

前言

官方通知

UIWebview即將不再可用,Apple開發(fā)者網(wǎng)站的新聞及更新頁面,2019年12月23日,已經(jīng)更新了UIWebview廢棄的最后通知,這次是必須適用wkwebview了。

webview跨域訪問安全漏洞

UIWebview可以加載本地圖片,但是其實(shí)這是個跨域訪問安全漏洞,還挺嚴(yán)重的,大家可以了解一下。

WKWebview更加安全,默認(rèn)allowFileAccessFromFileURLs是關(guān)閉的,導(dǎo)致一些需求場景下網(wǎng)頁中需要加載本地圖片資源的時候是無法直接加載的,我在這方面也遇到了一些問題,所以整理了一下搜到的常見的解決辦法,都一一驗(yàn)證了下,整合了一個demo,希望能幫到大家。
demo中有所有方案的演示代碼,代碼地址WKWebviewLoadLocalImages,如果覺得有用的話,可以點(diǎn)個star,謝謝。

WKWebview加載本地圖片4種方案:

方案1、資源放到沙盒tmp臨時文件夾下

loadHTMLString:baseURL方法加載html文本(html中有沙盒文件路徑),圖片需要存儲到沙盒tmp目錄下,baseURL參數(shù)傳入本地文件路徑的url,或者設(shè)置“file://”,圖片文件可以正常加載。
其他沙盒目錄(Cache、Library)即便在baseURL中進(jìn)行配置依然不能加載本地圖片。
方案1演示代碼

方案2、設(shè)置自定義的URLScheme

使用系統(tǒng)方法(iOS11之后的新方法)設(shè)置自定義url scheme,然后在代理方法中處理本地圖片的加載

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

1、在WKWebViewConfiguration中設(shè)置自己自定義的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標(biāo)簽對應(yīng)的src中的對應(yīng)本的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標(biāo)簽中的圖片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、代理方法中處理自定義協(xié)議的本地圖片的加載

把地址替換回本地圖片scheme:file,然后異步加載本地圖片,并把結(jié)果回傳給webview

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

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

    // scheme切換回本地文件協(xié)議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 {// 回傳結(jié)果給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了,網(wǎng)頁中的本地圖片圖片能正常展示了

方案3、直接把圖片數(shù)據(jù)轉(zhuǎn)成base64格式,轉(zhuǎn)換后的數(shù)據(jù)替換到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數(shù)據(jù)
        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]];
            
            /*
             下面這種方式必須指定準(zhǔn)確的文件地址或者圖片文件所在的目錄才能正常加載
             */
            [self.webView loadFileURL:localFileURL allowingReadAccessToURL:[localFileURL URLByDeletingLastPathComponent]];
        });
    }];

總結(jié)

上面列出的各種方法,只是把各種方案都的核心情況驗(yàn)證了一下,寫出的demo。在實(shí)際的項(xiàng)目中需要考慮html加載本地資源的具體情況,圖片本地緩存需要判斷緩存是否命中防止重復(fù)加載,多張圖片要考慮圖片的異步加載和刷新webview的實(shí)際,可能還有一些特殊情況可能沒有考慮到的,大家可以留言給我,我再補(bǔ)上。
最后再貼一下完整demo的地址:WKWebviewLoadLocalImages,覺得有用的可以star一下。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容