项目中,使用到web加载,是件再正常不过的事情.之前一直使用UIWebView.但ios8后,苹果推出了WKWebView.性能优化更加完善.并以更加稳定,加载滑动等功能方面更加流畅,内存占用也相对少而深受喜欢!今天详细扒一下WKWebView在项目中的使用.包含加载进度条设置,获取web界面标题,屏幕自适应,web界面是否允许跳转等功能实现!
直接粘代码:
.h文件
@interface WebVC : UIViewController
//添加外接属性,获取跳转url
@property(nonatomic,copy)NSString * urlStr;
@end
.m文件
//wkWebView
#import <WebKit/WebKit.h>
#import "WebVC.h"
//实现wk的协议方法,及滑动scrollView的协议方法
@interface WebVC () <WKNavigationDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property(nonatomic, strong)UIProgressView * progressView;
@end
@implementation JKWebVC
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//加载url
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
//添加kvo监听,获得页面title和加载进度值
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
//添加KVO监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//加载进度值
if ([keyPath isEqualToString:@"estimatedProgress"])
{
if (object == self.webView)
{
[self.progressView setAlpha:1.0f];
[self.progressView setProgress:self.webView.estimatedProgress animated:YES];
if(self.webView.estimatedProgress >= 1.0f)
{
[UIView animateWithDuration:0.5f
delay:0.3f
options:UIViewAnimationOptionCurveEaseOut
animations:^{
[self.progressView setAlpha:0.0f];
}
completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
//网页title
else if ([keyPath isEqualToString:@"title"])
{
if (object == self.webView)
{
self.navigationItem.title = self.webView.title;
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
self.progressView.hidden = NO;
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
[self.view bringSubviewToFront:self.progressView];
}
// WKNavigationDelegate 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//加载完成后隐藏progressView
self.progressView.hidden = YES;
//修改字体大小 300%
[ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '200%'" completionHandler:nil];
//修改字体颜色 #9098b8
[webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#222222'" completionHandler:nil];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
//加载失败同样需要隐藏progressView
self.progressView.hidden = YES;
[self.webView removeFromSuperview];
[self.view addSubview:self.blankPageView];
}
//点击跳转新界面
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
{
NSString * strRequest =[navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
if([strRequest isEqualToString:@"about:blank"]) {//主页面加载内容
decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
} else {//截获页面里面的链接点击
decisionHandler(WKNavigationActionPolicyAllow);//跳转
}
}
#pragma mark --------- 懒加载 --------------
- (void)viewDidLoad {
[super viewDidLoad];
}
- (WKWebView *)webView
{
if (!_webView) {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
//初始化偏好设置属性:preferences
config.preferences = [[WKPreferences alloc]init];
//The minimum font size in points default is 0;
config.preferences.minimumFontSize = 0;
//是否支持JavaScript
config.preferences.javaScriptEnabled = YES;
//不通过用户交互,是否可以打开窗口
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
//适应屏幕
NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController * wkUController =[[WKUserContentController alloc]init];
[wkUController addUserScript:wkUserScript];
config .userContentController =wkUController;
_webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, JkScreenWidth, JkScreenHeight) configuration:config];
_webView.scrollView.delegate = self;
_webView.backgroundColor = [UIColor whiteColor];
_webView.scrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:_webView];
}
return _webView;
}
-(UIProgressView *)progressView
{
if (!_progressView) {
_progressView =[[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, [[UIScreen mainScreen] bounds].size.width, 1)];
_progressView.backgroundColor = [UIColor whiteColor];
_progressView.progressTintColor= [UIColor redColor];//设置已过进度部分的颜色
_progressView.trackTintColor= [UIColor lightGrayColor];//设置未过进度部分的颜色
//设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
[self.view addSubview:_progressView];
}
return _progressView;
}
//移除监听者
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
[self.webView removeObserver:self forKeyPath:@"title"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}