iOS开发OC -- WKWebView的使用

项目中有的时候会用加载网页,简单记录一下,后续有需求会细化。

@property (nonatomic ,strong) WKWebView * webView;
@property (nonatomic, strong) UIProgressView * progView;

- (void)createView
{
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    //监测进度
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_model.url]]];
    [self.view addSubview:_webView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //进度条初始化
    _progView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
    _progView.backgroundColor = [UIColor blueColor];
    //设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.
    _progView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //没有进度的时候的颜色
    _progView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:_progView];
}

//进度条监控方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progView.progress = self.webView.estimatedProgress;
        if (self.progView.progress == 1) {
            /*
             *添加一个简单的动画,将progressView的Height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s,延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progView.hidden = YES;
                
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKWebView Delegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    // 页面开始加载时调用
    [self showProgressDialog];
    //开始加载网页时展示出progressView
    self.progView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progView];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    // 当内容开始返回时调用
    [self hideProgressDialog];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    // 页面加载完成之后调用
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
{
   // 页面加载失败时调用
    self.progView.hidden = YES;
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

你可能感兴趣的:(iOS开发OC -- WKWebView的使用)