先有被观察的对象存在
- (UIProgressView*)loadingProgressView {
if (!_loadingProgressView) {
_loadingProgressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 2)];
_loadingProgressView.progressTintColor = [UIColor redColor];
}
return _loadingProgressView;
}
注册监听 addObserver字符串随便写,类似于通知
//进度监听
[_wk_WebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
根据注册的监听,实现固定的方法observeValueForKeyPath
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//上面定义的字符串来匹配
if ([keyPath isEqualToString:@"estimatedProgress"]) {
_loadingProgressView.progress = [change[@"new"] floatValue];
if (_loadingProgressView.progress == 1.0) {
@weakify(self)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
@strongify(self)
self.loadingProgressView.hidden = YES;
});
}
}
}
//最后移除观察者 对象销毁 的时候 dealloc里面,
- (void)dealloc {
[_wk_WebView removeObserver:self forKeyPath:@"estimatedProgress"];
}