近期由于工作上在做一个文档预览的功能尝试了几个控件都不能满足需求,最后敲定用webview加载,然而加载txt出现了乱码,在这记录下个人的解决方法。
webview界面的基础设置
mWebView.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
判断并加载txt文件(txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt//不带的,可以依次尝试GBK和GB18030编)
NSString *lastName =[[filePath lastPathComponent] lowercaseString];
if ([lastName containsString:@".txt"]) {
//如果为UTF8格式的则body不为空
NSString *body =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//如果不是 则进行GBK编码再解码一次
if (!body) {
body =[NSString stringWithContentsOfFile:filePath encoding:0x80000632 error:nil]; } //不行用GB18030编码再解码一次
if (!body) {
body =[NSString stringWithContentsOfFile:filePath encoding:0x80000631 error:nil]; }
if (body) {
body =[body stringByReplacingOccurrencesOfString:@"\n" withString:@"
"];//替换换行符为HTML换行符
[mWebView loadHTMLString:body baseURL:nil]; } }
else{
NSURLRequest *request =[NSURLRequest requestWithURL:videoURL]; [mWebView loadRequest:request]; }
本文主要记录是本人解决txt乱码的一些常规处理方法,解析乱码后的一些HTML排版可根据需求替换相应的HTML标签(欢迎随时交流),webview的其他强大功能再次就不做过多介绍。