iOS-关于解决WebView、WKWEbView打开pdf文件乱码问题

今天遇到了WebView打开pdf乱码的问题,百度了一下,遂找到了解决方法,在这记录一下,原贴地址

原贴整理了两种解决方法,我试了第二种没成功,也没搞懂是什么问题,下面就整理一下第一种解决方法。

转成二进制文件

如果是WebView,要签代理

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *pageUrl = request.URL.absoluteString;
    NSString *lastName =[[pageUrl lastPathComponent] lowercaseString];
    
    if ([lastName containsString:@".pdf"])
    {
        NSData *data = [NSData dataWithContentsOfURL:request.URL];
        [self.webview loadData:data MIMEType:@"application/pdf" textEncodingName:@"GBK" baseURL:nil];
    }
    return YES;
}

如果是WKWebView,要签代理

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *_webUrlStr = navigationAction.request.URL.absoluteString;
    NSString *lastName =[[_webUrlStr lastPathComponent] lowercaseString];
    
    if ([lastName containsString:@".pdf"])
    {
        NSData *data = [NSData dataWithContentsOfURL:navigationAction.request.URL];
        [self.webView loadData:data MIMEType:@"application/pdf" characterEncodingName:@"GBK" baseURL:nil];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

 

你可能感兴趣的:(OC基础篇,webview,WKWebView,乱码,pdf,iOS)