UIWebview打开.txt文件中文乱码解决

用UIWebview打开txt文件有时候会出现乱码的情况,这种情况应该是txt的编码问题,解决方案如下:

txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt。带编码的用NSString的stringWithContentsOfFile可读出,不带的,我们依次尝试GBK和GB18030编码。

源码如下:

                    ///编码可以解决 .txt 中文显示乱码问题

                    NSStringEncoding *useEncodeing = nil;

                    //带编码头的如utf-8等,这里会识别出来

                    NSString *body = [NSString stringWithContentsOfFile:fileName usedEncoding:useEncodeing error:nil];

                    //识别不到,按GBK编码再解码一次.这里不能先按GB18030解码,否则会出现整个文档无换行bug。

                    if (!body) {

                        body = [NSString stringWithContentsOfFile:fileNameencoding:0x80000632 error:nil];

                    }

                    //还是识别不到,按GB18030编码再解码一次.

                    if (!body) {

                        body = [NSString stringWithContentsOfFile:fileNameencoding:0x80000631 error:nil];

                    }

                    

                    //展现

                    if (body) {

                        [webView_file loadHTMLString:body baseURL: nil];

                    }else {

                        NSString *urlString = [[NSBundle mainBundle]pathForAuxiliaryExecutable:fileName];

                        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

                        NSURL *requestUrl = [NSURL URLWithString:urlString];

                        NSURLRequest *request = [NSURLRequestrequestWithURL:requestUrl];

                        [webView_file loadRequest:request];

 

                    }

转载于:https://www.cnblogs.com/Camier-myNiuer/p/3521192.html

你可能感兴趣的:(UIWebview打开.txt文件中文乱码解决)