使用WKWebView加载.pdf,.DOC,.xls,.docx,.xlsx等格式文件

项目需求需要加载各种格式类型的文件,由于webView上架被限制,我们直接选择WKWebView。

//NAV_HEIGHT WIDTH这是项目中自己定义的宏 可根据自己情况设置WKWebView宽高
 self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.frame=CGRectMake(0, NAV_HEIGHT+2, WIDTH, HEIGHT-NAV_HEIGHT);  
//urlPath 是服务端的文件url,由于有的文件名有中文所以需要使用utf-8编码一下然后再转成URL,否则转的URL为nil,这个小坑浪费了有大半个小时才发现 哈哈哈
 NSString*urlPath=self.filePath;
 NSString *urlString = [NSString stringWithFormat:@"%@", urlPath];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
 [self.view addSubview:self.webView];

到这里基本的文件格式都可以加载了。
不过如果文件类型是TXT的 加载后会发现显示的界面乱码,txt文件(txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt//不带的,可以依次尝试GBK和GB18030编)这里就需要我们特殊处理一下,在加载url之前先进行判断

if([urlPath hasSuffix:@".txt"]){
//先进行NSUTF8StringEncoding编码
        NSString *body = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        if(!body){//如果没有编码成功再尝试GBK和GB18030编码
            NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            body = [NSString stringWithContentsOfURL:url encoding:enc error:nil];
        }
        if(body){
            [self.webView loadHTMLString:body baseURL:nil];
        }else{
            [self.webView loadRequest:request];
        }
}

到这里txt乱码问题就OK了,如果文件过大加载时间会有些慢,可以在加载文件的时候加入进度条,不然测试在这个界面一直等估计要炸毛,这里使用KVO来检测进度

[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
#pragma mark - event response
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ( [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.progressView.alpha = 1.0f;
        [self.progressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 self.progressView.alpha = 0.0f;
                             }
                             completion:^(BOOL finished) {
                                 [self.progressView setProgress:0 animated:NO];
                             }];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

到这里就结束了 上完整代码

#import "WebFileViewController.h"
#import 

@interface WebFileViewController ()
@property(nonatomic,strong)WKWebView*webView;
@property(nonatomic,strong)UIProgressView*progressView;
@end

@implementation WebFileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.frame=CGRectMake(0, NAV_HEIGHT+2, WIDTH, HEIGHT-NAV_HEIGHT);
    self.webView.navigationDelegate=self;
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
 NSString*file=self.filePath;
 NSString *urlString = [NSString stringWithFormat:@"%@",file];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
if([file hasSuffix:@".txt"]){
        NSString *body = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        if(!body){
            NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            body = [NSString stringWithContentsOfURL:url encoding:enc error:nil];
        }
        if(body){
            [self.webView loadHTMLString:body baseURL:nil];
        }else{
            [self.webView loadRequest:request];
        }
}else{
     [self.webView loadRequest:request];
}
 
   [self.view addSubview:self.webView];
   [self.view addSubview:self.progressView];

}
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ( [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.progressView.alpha = 1.0f;
        [self.progressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 self.progressView.alpha = 0.0f;
                             }
                             completion:^(BOOL finished) {
                                 [self.progressView setProgress:0 animated:NO];
                             }];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.frame = CGRectMake(0, NAV_HEIGHT, [UIScreen mainScreen].bounds.size.width, 2);
    }
    return _progressView;
}

- (void)dealloc {//最后别忘了销毁KVO监听
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
    [self.webView removeFromSuperview];
    self.webView=nil;
    self.webView.navigationDelegate=nil;
    
}

如果这篇文章对你有帮助,留个小爱心支持下吧,好了下班打卡走人。

你可能感兴趣的:(使用WKWebView加载.pdf,.DOC,.xls,.docx,.xlsx等格式文件)