ios WebView 打开txt文件乱码问题

      

 UIWebView *web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0,WIDTH , HEIGHT)];

    web.backgroundColor = [UIColor clearColor];

    web.scalesPageToFit = YES;

    web.scrollView.delegate = self;

    web.delegate = self;

    web.userInteractionEnabled = YES;



    

    ///编码可以解决 .txt 中文显示乱码问题
    NSStringEncoding *useEncodeing = nil;

    //带编码头的如utf-8等,这里会识别出来 self.path是文件地址(Users/a1/Library/Developer/CoreSimulator/Devices/62525235-2FB8-40D6-8B16-1F94704B7EEA/data/Containers/Data/Application/635003EB-D704-4EC4-8333-6CF80B5E3FCB/Documents/22237.text)

    NSString *body = [NSString stringWithContentsOfFile:self.path usedEncoding:useEncodeing error:nil];

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

    if (!body) {

        body = [NSString stringWithContentsOfFile:self.path  encoding:0x80000632 error:nil];

    }

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

    if (!body) {

        body = [NSString stringWithContentsOfFile:self.path encoding:0x80000631 error:nil];

    }

    

    //展现

    if (body) {

        [web loadHTMLString:body baseURL: nil];

    }else {

        NSURL *url = [NSURL fileURLWithPath:self.path];

        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];

        [web loadRequest:request];

    }

 

 

你可能感兴趣的:(iOS开发,ios,ios开发,webview,乱码)