關(guān)于WKWebview與UIWebview的簡單對比熬的,可以參考我去年寫的一篇文章WKWbeview的初步使用痊硕。
這次我們通過KVO來獲取網(wǎng)頁頁面title以及加載的進(jìn)度值,解釋可以看代碼的注釋押框,如下
#import "WKWebviewController.h"
#import <WebKit/WebKit.h>
@interface WKWebviewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic,strong) WKWebView *wkWebview;
@property (nonatomic,strong) UIProgressView *progress;
@end
@implementation WKWebviewController
#pragma mark --- wk
- (WKWebView *)wkWebview
{
if (_wkWebview == nil)
{
_wkWebview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
_wkWebview.UIDelegate = self;
_wkWebview.navigationDelegate = self;
_wkWebview.backgroundColor = [UIColor clearColor];
[self.view addSubview:_wkWebview];
}
return _wkWebview;
}
#pragma mark 加載進(jìn)度條
- (UIProgressView *)progress
{
if (_progress == nil)
{
_progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, 2)];
_progress.tintColor = [UIColor blueColor];
_progress.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_progress];
}
return _progress;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//TODO:加載
[self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
//TODO:kvo監(jiān)聽岔绸,獲得頁面title和加載進(jìn)度值
[self.wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
[self.wkWebview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark KVO的監(jiān)聽代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//加載進(jìn)度值
if ([keyPath isEqualToString:@"estimatedProgress"])
{
if (object == self.wkWebview)
{
[self.progress setAlpha:1.0f];
[self.progress setProgress:self.wkWebview.estimatedProgress animated:YES];
if(self.wkWebview.estimatedProgress >= 1.0f)
{
[UIView animateWithDuration:0.5f
delay:0.3f
options:UIViewAnimationOptionCurveEaseOut
animations:^{
[self.progress setAlpha:0.0f];
}
completion:^(BOOL finished) {
[self.progress setProgress:0.0f animated:NO];
}];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
//網(wǎng)頁title
else if ([keyPath isEqualToString:@"title"])
{
if (object == self.wkWebview)
{
self.title = self.wkWebview.title;
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark 移除觀察者
- (void)dealloc
{
[self.wkWebview removeObserver:self forKeyPath:@"estimatedProgress"];
[self.wkWebview removeObserver:self forKeyPath:@"title"];
}
@end
代碼不足之處,還請多多指教橡伞。