WkWebView 预览各种文件

    xiaoxiao2021-03-25  121

    最近项目中加入了一个网盘功能,需要对各种文件进行预览 在加载txt文件时会发现出现乱码,其他都正常的 后来发现txt的解码方式不一样,所以做了如下处理

    - (void)viewDidLoad { [super viewDidLoad]; self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; self.webView.allowsBackForwardNavigationGestures = YES; self.webView.navigationDelegate = self; [self.view addSubview:self.webView]; [MBProgressHUD showMessage:@"正在解码,请稍后"]; NSString *str = [self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *subStr = [str substringFromIndex:str.length-3]; NSURL *url = [NSURL URLWithString:str]; if ([subStr isEqualToString:@"txt"]) { NSStringEncoding * usedEncoding = nil; //带编码头的如 utf-8等 这里会识别 NSString *body = [NSString stringWithContentsOfURL:url usedEncoding:usedEncoding error:nil]; if (!body) { //如果之前不能解码,现在使用GBK解码 NSLog(@"GBK"); body = [NSString stringWithContentsOfURL:url encoding:0x80000632 error:nil]; } if (!body) { //再使用GB18030解码 NSLog(@"GBK18030"); body = [NSString stringWithContentsOfURL:url encoding:0x80000631 error:nil]; } if (body) { [self.webView loadHTMLString:body baseURL:nil]; //[self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } else { NSLog(@"没有合适的编码"); [self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } }else { [self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } } - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { [MBProgressHUD hideHUD]; NSLog(@"didStartProvisionalNavigation"); }
    转载请注明原文地址: https://ju.6miu.com/read-9599.html

    最新回复(0)