前言
官方通知
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一下。