最近做資料文件下載下來(lái)并查看的時(shí)候,用 WKWebView 打開(kāi)office 類型的文件的時(shí)候是沒(méi)問(wèn)題的,但是打開(kāi)測(cè)試人員上傳的一個(gè) TXT/PDF 文件就出現(xiàn)了亂碼問(wèn)題,經(jīng)過(guò)查看,應(yīng)該是文件的編碼問(wèn)題,于是找了兩種方式來(lái)解決出現(xiàn)的問(wèn)題。
1、轉(zhuǎn)成二進(jìn)制文件
- (void)loadURL:(NSURL *)pageURL {
NSString *fileType = [[pageURL lastPathComponent] lowercaseString];
if ([fileType hasSuffix:@".txt"]) {
NSData *data = [NSData dataWithContentsOfURL:pageURL];
[self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"GBK" baseURL:nil];
} else if ([fileType hasSuffix:@".pdf"]){
NSData *data = [NSData dataWithContentsOfURL:pageURL];
[self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"GBK" baseURL:nil];
} else {
[self.webView loadRequest:[NSURLRequest requestWithURL:pageURL]];
}
}
官方文檔對(duì)這個(gè)方法的解釋:
一個(gè)WKNavigation對(duì)象包含信息跟蹤加載一個(gè)網(wǎng)頁(yè)的進(jìn)展。
A WKNavigation object contains information for tracking the loading progress of a webpage.
導(dǎo)航web視圖加載方法返回的對(duì)象,也是傳遞到導(dǎo)航委托方法來(lái)唯一地標(biāo)識(shí)一個(gè)網(wǎng)頁(yè)加載從開(kāi)始到結(jié)束。它沒(méi)有自己的方法或?qū)傩浴?br> A navigation object is returned from the web view load methods and is also passed to the navigation delegate methods to uniquely identify a webpage load from start to finish. It has no method or properties of its own.
2、對(duì)文件進(jìn)行轉(zhuǎn)碼
NSString *lastName =[[_webUrlStr lastPathComponent] lowercaseString];
if ([lastName containsString:@".txt"]) {
///編碼可以解決 .txt 中文顯示亂碼問(wèn)題
NSStringEncoding *useEncodeing = nil;
//帶編碼頭的如utf-8等,這里會(huì)識(shí)別出來(lái)
NSString *body = [NSString stringWithContentsOfFile:_webUrlStr usedEncoding:useEncodeing error:nil];
//識(shí)別不到,按GBK編碼再解碼一次.這里不能先按GB18030解碼,否則會(huì)出現(xiàn)整個(gè)文檔無(wú)換行bug。
if (!body) {
body = [NSString stringWithContentsOfFile:_webUrlStr encoding:0x80000632 error:nil];
}
//還是識(shí)別不到,按GB18030編碼再解碼一次.
if (!body) {
body = [NSString stringWithContentsOfFile:_webUrlStr encoding:0x80000631 error:nil];
}
//展現(xiàn)
if (body) {
NSString* responseStr = [NSString stringWithFormat:
@"<HTML>"
"<head>"
"<title>Text View</title>"
"</head>"
"<BODY>"
"<pre>"
"%@"
"</pre>"
"</BODY>"
"</HTML>",
body];
[self.webView loadHTMLString:responseStr baseURL:nil];
}else {
NSString *urlString = [[NSBundle mainBundle] pathForAuxiliaryExecutable:_webUrlStr];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *requestUrl = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
[self.webView loadRequest:request];
}
}