一个KVO 实现WKWebView加载进度条的例子 (注意最后移除观察者)
//
// OpenWebViewController.m
// Treasure
//
// Created by 蓝蓝色信子 on 16/7/29.
// Copyright © 2016年 GY. All rights reserved.
// #import "ZTOpenWebViewController.h"
#import <WebKit/WebKit.h> @interface ZTOpenWebViewController ()<WKNavigationDelegate>
//{
// //网页视图
// UIWebView * _webView;
//}
@property (strong, nonatomic) WKWebView *webView; @property (strong, nonatomic) UIProgressView *progressView; @end @implementation ZTOpenWebViewController - (void)viewDidLoad {
[super viewDidLoad];
// //取消导航栏的影响
self.automaticallyAdjustsScrollViewInsets = NO;
self.view.backgroundColor = [UIColor whiteColor]; //[SVProgressHUD show];
//实例化
[self createWebView]; [self creatCustomProgressView];
} -(void)creatCustomProgressView{ //增加加载进度条
// KVO,监听webView属性值得变化(estimatedProgress,title为特定的key)
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; // UIProgressView初始化
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progressView.frame = CGRectMake(, , _webView.frame.size.width, );
self.progressView.trackTintColor = [UIColor clearColor]; // 设置进度条的色彩
self.progressView.progressTintColor = [UIColor magentaColor];
// 设置初始的进度,防止用户进来就懵逼了(微信大概也是一开始设置的10%的默认值)
[self.progressView setProgress:0.1 animated:YES];
[_webView addSubview:self.progressView];
} - (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:NO animated:NO];
[super viewWillAppear:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
[SVProgressHUD dismiss];
[super viewWillDisappear:animated];
} - (void)createWebView
{
_webView = [[WKWebView alloc]initWithFrame:self.view.bounds]; [self.view addSubview:_webView]; //调整适应比例
//_webView.scalesPageToFit = YES;
//设置代理
_webView.navigationDelegate = self;
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0]]; }
#pragma mark - WKWebView NavigationDelegate //WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//NSLog(@"是否允许这个导航");
decisionHandler(WKNavigationActionPolicyAllow);
} - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
// Decides whether to allow or cancel a navigation after its response is known. //NSLog(@"知道返回内容之后,是否允许加载,允许加载");
decisionHandler(WKNavigationResponsePolicyAllow);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
//NSLog(@"开始加载");
//self.progress.alpha = 1; //[SVProgressHUD show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
//NSLog(@"跳转到其他的服务器"); } - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
//NSLog(@"网页由于某些原因加载失败");
//[SVProgressHUD dismiss];
//self.progress.alpha = 0;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
//NSLog(@"网页开始接收网页内容");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
//NSLog(@"网页导航加载完毕");
//[SVProgressHUD dismiss];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; self.title = webView.title;
[webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable ss, NSError * _Nullable error) {
//NSLog(@"----document.title:%@---webView title:%@",ss,webView.title);
}];
//self.progress.alpha = 0; } - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
//NSLog(@"加载失败,失败原因:%@",[error description]);
//self.progress.alpha = 0;
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
//NSLog(@"网页加载内容进程终止");
} #pragma mark - KVO监听
// 第三部:完成监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([object isEqual:_webView] && [keyPath isEqualToString:@"estimatedProgress"]) { // 进度条 CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
//NSLog(@"打印测试进度值:%f", newprogress); if (newprogress == ) { // 加载完成
// 首先加载到头
[self.progressView setProgress:newprogress animated:YES];
// 之后0.3秒延迟隐藏
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ weakSelf.progressView.hidden = YES;
[weakSelf.progressView setProgress: animated:NO];
}); } else { // 加载中
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
} else if ([object isEqual:_webView] && [keyPath isEqualToString:@"title"]) { // 标题 //self.title = _webView.title;
} else { // 其他 [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
} -(void)dealloc{
NSLog(@"webVC dealloc = %@",self);
[_webView removeObserver:self forKeyPath:@"estimatedProgress"];
[_webView removeObserver:self forKeyPath:@"title"];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} /*
#pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/ @end
一个KVO 实现WKWebView加载进度条的例子 (注意最后移除观察者)的更多相关文章
- iOS WKWebView 加载进度条、导航栏返回&关闭 (Swift 4)
		
导航: 1.加载进度条 2.导航栏增加返回.关闭按钮 加载进度条 效果图 代码如下: self.progressView.trackTintColor = UIColor.white self.pro ...
 - iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26
		
1.由于项目中加载网络插件,直接使用了webview加载.使用了三方NJKWebViewProgress进度条的使用,近期在测试时发现,网络缓慢时出现白屏,有卡顿现象. 于是采用了WKWebView进 ...
 - css3 linear-gradient实现页面加载进度条效果
		
最终效果图: html结构: <div> <p class="p1"> <span></span> < ...
 - pace.js – 加载进度条插件
		
这儿只是简单介绍一下这个插件pace.js. 在页面中引入Pace.js,页面就会自动监测你的请求(包括Ajax请求),在事件循环滞后,会在页面记录加载的状态以及进度情况.此插件的兼容性很好,可以兼容 ...
 - 仿UC浏览器图片加载进度条
		
前几天用UC浏览器看新闻(无意中给UC打了广告),看到它的图片加载进度条,正好最近有时间,所以就自己写了一个. 效果图如下 进度条的底色和填充颜色都可以调整. 首先中间的笑脸作为一个整体,其实现代码如 ...
 - 【Web前沿技术】纯 CSS3 打造的10个精美加载进度条动画
		
之前向大家介绍8款优秀的 jQuery 加载动画和进度条插件,今天这篇文章向大家推荐10个纯 CSS3 代码实现精美加载进度条动画效果的方案.加载动画和进度条在网站和 Web 应用中的使用非常流行,特 ...
 - jQuery模拟页面加载进度条
		
因为我们无法通过任何方法获取整个页面的大小和当前加载了多少,所以想制作一个加载进度条的唯一办法就是模拟.那要怎么模拟呢? 我们知道,页面是从上往下执行的,也就是说我们可以大致估算出在页面的某个位置加载 ...
 - 混合开发(一)——WebView开发高级技巧之加载网页以及JavaScript,加载进度条
		
混合开发(一)--WebView开发高级技巧之加载网页以及JavaScript,加载进度条 现在关于混合开发也越来越多了,很多人喜欢跟随,比如HB,比如RN,其实这东西很早就有这么一个概念了,而且说实 ...
 - Unity3D 场景切换加载进度条实现
		
需要三个场景,场景A,场景B,场景C: 场景A:一个按钮,点击加载场景B: 场景B:从A切换到C过度场景,加载进度条: 场景C:目标场景: 创建OnProgress.cs脚本: using Syste ...
 
随机推荐
- tar命令: 解压到指定的目录, 解压并删除原tar文件
			
-f: 置顶文件名, 后面不能再跟其他选项字母了,必须是文件名, 但是再在这个后面又可以跟 -? 选项: -C: 指定解压到的目的目录 不是-c, 小写的-c是创建. -p保留原来文件的属性. tar ...
 - Vue音乐播放器(三):项目目录介绍,以及图标字体、公共样式等资源准备
			
我们所有的开发都是基于修改src下面的目录 里面的文件去做开发即可 stylus的使用是需要下载stylus-loader的包的 渲染效果 配置修改eslintrc.js 配置了webpack.bas ...
 - mongotemplate 简单使用
			
怎么说呢,工作需要,不可能给你慢慢学的时间,一切以先解决当前jira为前提, mondb 安装不说了网上一搜就有,推荐图形管理界面 robo3t 比较直观 1.多条件查询这个比较简单 有两种方法 1C ...
 - python进行数据库迁移的时候显示(TypeError: __init__() missing 1 required positional argument: 'on_delete')
			
进行数据库迁移的时候,显示 TypeError: __init__() missing 1 required positional argument: 'on_delete' 图示: 出现原因: 在 ...
 - centos输入正确的账号和密码登陆不进去
			
vm下启动centos,输入正确的账号和密码,依然登陆不进去,一直处于这个界面: 暂时的解决方法是:先等待一段时间.重启,然后再输入密码,然后,ctrl+c 不停地ctrl+c,然后就登陆进去了.什么 ...
 - 在静态页面中使用 Vue.js
			
在静态页面中使用 Vue.js 不使用Node.js, NPM, Webpack 等, 在静态页中使用Vue.js. 包括路由, 单文件组件. 1. 创建index.html index.html做为 ...
 - SpringBoot使用RestTemplate基础认证
			
SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...
 - GCD and LCM HDU 4497 数论
			
GCD and LCM HDU 4497 数论 题意 给你三个数x,y,z的最大公约数G和最小公倍数L,问你三个数字一共有几种可能.注意123和321算两种情况. 解题思路 L代表LCM,G代表GCD ...
 - dp(动态规划之最佳路径+dfs)
			
http://acm.hdu.edu.cn/showproblem.php?pid=1078 FatMouse and Cheese Time Limit: 2000/1000 MS (Java/Ot ...
 - 通过设置代理解决AndroidStudio无法下载gradle问题
			
一.AndroidStudio代理 我们平时在使用android studio时,难免需要从android官网下载一些项目运行所需要的SDK文件,但是因为android官网在国外,访问起来会比较慢,所 ...