监听webView的加载进度

作者: ZhengYaWei | 来源:发表于2017-02-26 11:21 被阅读403次

    实际项目中可能会用到进度条来显示一个网页的加载进度,不知道的人还以为有什么很神奇的地方,其实很简单,主要是通过监听webView的一个属性estimatedProgress。直接上代码吧,代码量很少的。

    @property (weak, nonatomic) WKWebView *webView;
    @property (weak, nonatomic) CALayer *progresslayer;
    

    界面布局。

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
        self.automaticallyAdjustsScrollViewInsets = NO;
        WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 63, self.view.frame.size.width, self.view.frame.size.height - 64)];
        [self.view addSubview:webView];
        self.webView = webView;
        //添加属性监听
        [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        
        //进度条
        UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];
        progress.backgroundColor = [UIColor clearColor];
        [self.view addSubview:progress];
    
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, 0, 3);
        layer.backgroundColor = [UIColor blueColor].CGColor;
        [progress.layer addSublayer:layer];
        self.progresslayer = layer;
        
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://bing.com"]]];
    }
    
    

    监听进度,更新界面。

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            //NSLog(@"%@", change);
            self.progresslayer.opacity = 1;
            self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[NSKeyValueChangeNewKey] floatValue], 3);
            if ([change[NSKeyValueChangeNewKey] floatValue] == 1) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.progresslayer.opacity = 0;
                });
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
                });
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    
    

    温馨提示,不要忘记dealloc了。

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

    so easy!!!!!!!!!

    相关文章

      网友评论

      本文标题:监听webView的加载进度

      本文链接:https://www.haomeiwen.com/subject/xueowttx.html