比UIWebView更强大好用的WKWebView

355 阅读1分钟

WKWebView 是IOS8新增的 Web浏览视图

WKWebView相对于UIWebView强大了很多,内存的消耗相对少了,所提供的接口也丰富了。 title,estimatedProgress是两个很有用的新API

#import "MYWebViewController.h"
#import <WebKit/WebKit.h>

@interface MYWebViewController ()
//进度条
@property (weak, nonatomic) IBOutlet UIProgressView
*progressView;
@property (nonatomic, weak) WKWebView *webView;

@end

@implementation MYWebViewController
/*
    使用步骤
    1.导入WebKit框架
    2.导入WebKit/WebKit.h头文件
 */
- (void)viewDidLoad {
    [superviewDidLoad];
    
    //添加WKWebView
    WKWebView*webView = [[WKWebViewalloc] initWithFrame:self.view.bounds];
   _webView = webView;
    [self.viewinsertSubview:webView atIndex:0];

    //加载网页
    NSURLRequest*request = [NSURLRequestrequestWithURL:_url];
    [webViewloadRequest:request];

    //KVO: 让self对象监听webView的estimatedProgress
    [webView addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];
}

// 只要监听的属性有新值就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id>
*)change context:(void *)context
{
    _progressView.progress= _webView.estimatedProgress;
    _progressView.hidden= _progressView.progress>= 1;
}

// KVO一定要移除观察者
- (void)dealloc
{
[self.webViewremoveObserver:selfforKeyPath:@"estimatedProgress"];
}

@end

QQ20150411-1@2x.png