把一份文字檔放進 App bundle 再用 UIWebView 顯示,看似簡單,實務上最容易翻車的地方是編碼——UTF-8 的檔還好,一旦是 GBK 或 GB18030 編碼,畫面上就是一堆亂碼。本文示範一個會自動逐層嘗試編碼的讀取流程。
- (void)loadTxt {
self.myWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,
[UIScreen mainScreen].bounds.size.width,
[UIScreen mainScreen].bounds.size.height + 60)];
NSString *txtPath = [[NSBundle mainBundle] pathForResource:@"city_list" ofType:@"txt"];
NSLog(@"txtPath:%@", txtPath);
// 逐層嘗試編碼,可解決 .txt 中文顯示亂碼的問題
NSStringEncoding usedEncoding = 0;
// 帶有 BOM 或編碼頭的檔案(如 UTF-8),這裡會自動被辨識出來
NSString *body = [NSString stringWithContentsOfFile:txtPath
usedEncoding:&usedEncoding
error:nil];
// 若辨識失敗,改用 GBK 再解一次。
// 注意:這裡不能先嘗試 GB18030,否則會出現整個文件失去換行的問題。
if (!body) {
body = [NSString stringWithContentsOfFile:txtPath
encoding:0x80000632 // GBK
error:nil];
}
// 還是失敗,再改用 GB18030 解一次
if (!body) {
body = [NSString stringWithContentsOfFile:txtPath
encoding:0x80000631 // GB18030
error:nil];
}
if (body) {
// 有可能這份 txt 其實是 JSON 格式的資料
NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
id userData = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
if ([userData isKindOfClass:[NSDictionary class]]) {
// 範例結構:
// {"code":"000000","memo":"成功",
// "result":{"domestic":[{"cityId":"110100","cityName":"北京市",
// "region":[{"regionId":"110101","regionName":"東城區"}, ...]}, ...]}}
NSArray *domesticArray = [(NSDictionary *)userData objectForKey:@"domestic"];
for (NSDictionary *dict in domesticArray) {
// 在這裡建立對應的 model 並寫入資料
}
}
[self.myWebview loadHTMLString:body baseURL:nil];
} else {
// 三種編碼都失敗,改用檔案 URL 直接載入,交給系統判斷
NSString *urlString = [[NSBundle mainBundle] pathForAuxiliaryExecutable:txtPath];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *requestUrl = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
[self.myWebview loadRequest:request];
}
[self.view addSubview:self.myWebview];
}
為什麼順序是「自動偵測 → GBK → GB18030」?GB18030 是 GBK 的超集,相容範圍更廣,但也更容易「吃掉」不該吃的中文字元。實測若先丟 GB18030,某些檔案會出現全篇沒有換行的情況,所以把它排在最後一順位。
0x80000632 與 0x80000631 是什麼?這是 CFString 的編碼常數值,分別對應 GBK 與 GB18030。直接寫成十六進位可以避免引入 CoreFoundation 的額外標頭,但可讀性較差,實務上建議搭配註解,或改用 CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) 這種具名常數。
UIWebView 已不建議使用。若只是要顯示純文字,用 UITextView 或 UILabel 會更輕量;若需要呈現 HTML,請改用 WKWebView,並以 loadHTMLString:baseURL: 或 loadFileURL:allowingReadAccessToURL: 載入。以 WKWebView 顯示 bundle 內本機檔案時,務必透過 read access 參數授權可讀目錄,否則資源會載不進來。
字串長度限制。stringWithContentsOfFile: 系列 API 一次把整份檔案讀進記憶體,適合小型設定檔;若要處理大型文字檔,建議改用 NSInputStream 或 dispatch_io 逐段讀取。