wkwebview添加进度条

@interface CommonWebVC()<WKUIDelegate,WKNavigationDelegate, NJKWebViewProgressDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView wvMainWeb;
@property (nonatomic)NJKWebViewProgress
progressProxy;
@property (nonatomic)NJKWebViewProgressView* progressView;
@end

NJKWebViewProgressView 可以直接在网上搜索NJKWebViewProgressView

具体实现如下:

- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.wvMainWeb];
}

- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
_progressViewColor = Color_Theme;
[self.navigationController.navigationBar addSubview:self.progressView];

//清缓存 
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];

if (self.needRefresh) {
    [self loadData];
}
if (_isHiddenPopGes) {
    //禁止侧滑效果
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;

    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];

   [self.view addGestureRecognizer:pan];
  }
}

- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.progressView removeFromSuperview];


if (_isCartoon) {
//点击导航栏返回按钮的时候调用,所以Push出的控制器最好禁用侧滑手势:
CTAppDelegate * appDelegate = (CTAppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = 2;//关闭横屏仅允许竖屏
//切换到竖屏
[self orientationToPortrait:UIInterfaceOrientationPortrait];
}
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:Color_Title_333,NSFontAttributeName:Font_Navigationbar_Title}];
self.navigationController.navigationBar.barTintColor = Color_White;//[XLUtil colorwithHexString:@"#FFFFFF"];
[self.leftBtn setImage:ImageNamed(@"navigationBar_popBack") forState:(UIControlStateNormal)];
if (_hiddenNav) {
    if (!_superNav) {
        [self.navigationController setNavigationBarHidden:NO animated:_leftrightNav?NO:animated];
        !self.blockHidden?:self.blockHidden();
    }
}
if (!_isNoReload) {
    [self.wvMainWeb reload];//播放视频类的都需要reload
}
}


// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

NSLog(@"开始加载网页");

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:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{

NSLog(@"加载失败");
   //加载失败同样需要隐藏progressView
   self.progressView.hidden = YES;
}

// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
//这句是必须加上的,不然会异常
decisionHandler(actionPolicy);

}
 // 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

//这句是必须加上的,不然会异常

decisionHandler(WKNavigationActionPolicyAllow);
return;
}
 //WkWebView的 title
  -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"title"]) {
    if (object == self.wvMainWeb) {
        if (self.isTab) {
            self.navigationItem.title = self.wvMainWeb.title;
        }else{
            self.title = self.wvMainWeb.title;
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}else if([keyPath isEqualToString:@"estimatedProgress"]){//监测进度
    
    self.progressView.progress = self.wvMainWeb.estimatedProgress;

    if (self.progressView.progress == 1) {
        /*
         *添加一个简单的动画,将progressView的Height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍
         *动画时长0.25s,延时0.3s后开始动画
         *动画结束后将progressView隐藏
         */
        __weak typeof (self)weakSelf = self;
        
        weakSelf.progressView.hidden = YES;

   //            [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];
}
 }


-(NJKWebViewProgressView*)progressView{
if (!_progressView) {
    CGFloat progressBarHeight = 2;
    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height - progressBarHeight - 0.5, navigaitonBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.progressColor = self.progressViewColor;
    _progressView.progress = 0;
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
}
return _progressView;
}

-(NJKWebViewProgress*)progressProxy{
if (!_progressProxy) {
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.progressDelegate = (id)self;
}
return _progressProxy;
}

- (WKWebView *)wvMainWeb {
if (!_wvMainWeb) {
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
 
  configuration.preferences = [[WKPreferences alloc] init];

    //add by xinle 处理js和OC交互
    configuration.preferences.javaScriptEnabled = YES;//是否支持JS
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;//不通过用户交互是否可以打开窗口
    configuration.processPool = [[WKProcessPool alloc] init];

    configuration.userContentController = [WKUserContentController new];

    //JS调用OC 添加处理脚本(goToApp是与h5约定好的消息名称)
      [configuration.userContentController addScriptMessageHandler:[[WebJsDelegate alloc]initWithScriptTarget:self] name:@"share"];
      
      //返回事件
      [configuration.userContentController addScriptMessageHandler:[[WebJsDelegate alloc]initWithScriptTarget:self] name:@"h5Back"];
      
      configuration.allowsInlineMediaPlayback = YES;
    
    configuration.mediaPlaybackRequiresUserAction = NO;
      //返回事件
         [configuration.userContentController addScriptMessageHandler:[[WebJsDelegate alloc]initWithScriptTarget:self] name:@"h5StartBack"];
    
    _wvMainWeb = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    _wvMainWeb.UIDelegate = self;
    _wvMainWeb.navigationDelegate = self;
    _wvMainWeb.backgroundColor = [UIColor clearColor];
    if ([UIScrollView instancesRespondToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [_wvMainWeb.scrollView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@2];
    }
    //title监听
    [_wvMainWeb addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    //监测进度显示
    [self.wvMainWeb addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
return _wvMainWeb;
}

猜你喜欢

转载自blog.csdn.net/weixin_42050662/article/details/110952407