欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS-WKWebview 带有进度条加载的ViewController【KVO监听Webview加载进度】

程序员文章站 2022-04-30 21:37:37
前言 为什么要说 WKWebview,在之前做电子书笔记时已经提过 WKWebview 在iOS8之后已完全替代 Webview,原因就不多说了,主要还是内存过大; 封装 封装一个基于 UIViewController 类: WKWebViewController WKWebViewControll ......

iOS-WKWebview 带有进度条加载的ViewController【KVO监听Webview加载进度】

 

前言

为什么要说 WKWebview,在之前做电子书笔记时已经提过 WKWebview 在iOS8之后已完全替代 Webview,原因就不多说了,主要还是内存过大;

封装

封装一个基于 UIViewController 类: WKWebViewController

WKWebViewController.h

@interface WKWebViewController : UIViewController
///目标URL
@property (nonatomic,strong) NSString *url;
@property (nonatomic,strong) WKWebView *webview;
@end

WKWebViewController.m

#import "WKWebViewController.h"

@interface WKWebViewController ()<WKNavigationDelegate,UIScrollViewDelegate>
///进度条
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    ///添加 KVO 对进度监听
    [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.webview];
    [self.view addSubview:self.progressView];
    
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webview.estimatedProgress;
        if (self.progressView.progress == 1) {
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - webview 代理
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //加载完成隐藏progressView
    self.progressView.hidden = YES;
}
//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
    //加载失败隐藏progressView
    self.progressView.hidden = YES;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return nil;
}
#pragma mark - 属性
- (WKWebView *)webview{
    if (!_webview) {
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        // 自适应屏幕宽度js
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        // 添加自适应屏幕宽度js调用的方法
        [wkWebConfig.userContentController addUserScript:wkUserScript];
        _webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - (wkj_IsIphoneX ? 88 + 33 : 64)) configuration:wkWebConfig];
        _webview.navigationDelegate = self;
        _webview.scrollView.delegate = self;
        _webview.opaque = NO;
    }
    return _webview;
}
- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
        _progressView.trackTintColor = [ColorKLSystem colorWithAlphaComponent:0.5];
        _progressView.tintColor = ColorKLSystem;
        _progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    }
    return _progressView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end