//
// 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加载进度条的例子 (注意最后移除观察者)的更多相关文章

  1. iOS WKWebView 加载进度条、导航栏返回&关闭 (Swift 4)

    导航: 1.加载进度条 2.导航栏增加返回.关闭按钮 加载进度条 效果图 代码如下: self.progressView.trackTintColor = UIColor.white self.pro ...

  2. iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26

    1.由于项目中加载网络插件,直接使用了webview加载.使用了三方NJKWebViewProgress进度条的使用,近期在测试时发现,网络缓慢时出现白屏,有卡顿现象. 于是采用了WKWebView进 ...

  3. css3 linear-gradient实现页面加载进度条效果

    最终效果图: html结构: <div>    <p class="p1">        <span></span>    < ...

  4. pace.js – 加载进度条插件

    这儿只是简单介绍一下这个插件pace.js. 在页面中引入Pace.js,页面就会自动监测你的请求(包括Ajax请求),在事件循环滞后,会在页面记录加载的状态以及进度情况.此插件的兼容性很好,可以兼容 ...

  5. 仿UC浏览器图片加载进度条

    前几天用UC浏览器看新闻(无意中给UC打了广告),看到它的图片加载进度条,正好最近有时间,所以就自己写了一个. 效果图如下 进度条的底色和填充颜色都可以调整. 首先中间的笑脸作为一个整体,其实现代码如 ...

  6. 【Web前沿技术】纯 CSS3 打造的10个精美加载进度条动画

    之前向大家介绍8款优秀的 jQuery 加载动画和进度条插件,今天这篇文章向大家推荐10个纯 CSS3 代码实现精美加载进度条动画效果的方案.加载动画和进度条在网站和 Web 应用中的使用非常流行,特 ...

  7. jQuery模拟页面加载进度条

    因为我们无法通过任何方法获取整个页面的大小和当前加载了多少,所以想制作一个加载进度条的唯一办法就是模拟.那要怎么模拟呢? 我们知道,页面是从上往下执行的,也就是说我们可以大致估算出在页面的某个位置加载 ...

  8. 混合开发(一)——WebView开发高级技巧之加载网页以及JavaScript,加载进度条

    混合开发(一)--WebView开发高级技巧之加载网页以及JavaScript,加载进度条 现在关于混合开发也越来越多了,很多人喜欢跟随,比如HB,比如RN,其实这东西很早就有这么一个概念了,而且说实 ...

  9. Unity3D 场景切换加载进度条实现

    需要三个场景,场景A,场景B,场景C: 场景A:一个按钮,点击加载场景B: 场景B:从A切换到C过度场景,加载进度条: 场景C:目标场景: 创建OnProgress.cs脚本: using Syste ...

随机推荐

  1. Stream 源码分析

    Stream 支持顺序和并行聚合操作的一组元素序列. 1)operations:支持在单个元素上执行的操作,流操作分为中间操作和终止操作 1-1)中间操作: 1-1-1)无状态:unordered() ...

  2. tcpdump中文帮助

    TCPDUMP(8)                                            System Manager's Manual                        ...

  3. tensorflow和keras的安装

    1 卸载tensorflow方法,在终端输入:  把protobuf删除了才能卸载干净. sudo pip uninstall protobuf sudo pip uninstall tensorfl ...

  4. VS2012下自定义打开文件对话框

    VS2012下自定义打开文件对话框,MFC的CFileDialog封装了太多,太复杂,绕得头晕,自己封装一个得了 #pragma once #include <objbase.h> #in ...

  5. Shell脚本中的特殊字符(美元符、反斜杠、引号等)作用介绍

    Shell中的特殊字符有 1.$ 美元符 2.\ 反斜杠 3.` 反引号 4." 双引号 5.< ,>;,*,?,[,] 下面我一一举列说明 一.$符号 1.echo $? 显示 ...

  6. mysql新建表

    CREATE TABLE table( id int(20) not null auto_increment primary key, //auto_increment当为空时自动补全,注意,类型应该 ...

  7. SoapUI学习之SOAP和REST的区别

    一.Soap和Rest的定义 SOAP(Simple Object Access Protocol 简单对象访问协议),用于在Web Service中把远程调用和返回封装成机器可读的格式化数据,事实上 ...

  8. css的继承之width属性(容易忽略)

    众所周知,css的三大特性分别是 继承性,层叠性,和优先级. 那么这里就详细说一下css中width的继承性及其特殊情况. 继承性概念详解:css的继承性指的被包在内部的标签拥有外部标签的样式性,子元 ...

  9. 解决在Tomcat中的server.xml中修改了配置,启动后还原的问题

    正确答案,你要在eclipse的项目Servers中,找到你的tomcat,打开有各种配置文件,在这里改,才会在使用eclipse启动tomcat后不会自动恢复.

  10. Java集合概括总结及集合选用

    Collection 1. List ArrayList :Object数组,是一个数组队列,相当于动态数组.它由数组实现,随机访问效率高,随机插入.随机删除效率低. LinkedList :是一个双 ...