//
//  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(0, 0, _webView.frame.size.width, 5);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 == 1) { // 加载完成// 首先加载到头
            [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:0 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

转载于:https://www.cnblogs.com/liuw-flexi/p/9593716.html

一个KVO 实现WKWebView加载进度条的例子 (注意最后移除观察者)相关推荐

  1. WKWebView加载进度条(仿微信)

    WKWebView添加了estimatedProgress属性(double类型),我们可以利用该属性来设置UIProgressView github代码仓库上存放的Demo 为页面添加UIProgr ...

  2. WKWebView Safari调试、JS互调、加载进度条、JS中alert、confirm、prompt

    主要内容 Safari调试 swift/OC与JS互调 增加加载进度条 支持JS中alert.confirm.prompt Safari调试 设置 -> safari --> 高级,开启J ...

  3. [html] 请实现一个网站加载进度条

    [html] 请实现一个网站加载进度条 import { memo } from 'react'; import { useLifecycles } from 'react-use'; import ...

  4. NProgress.js - 前端全站进度条插件 - 给你的网站添加一个加载进度条

    0x00 前言 前几天给博客换了@Veen Zhao大佬的Cuteen主题,非常好看,但是因为不想让自己的博客和其他人的千篇一律,于是决定在Cuteen主题的前提下逐渐设计一些自己需要的东西.正巧前几 ...

  5. 小米视频加载进度条效果实现

    原文:小米视频加载进度条效果实现 好吧,其实这些都是我闲暇时自己做着玩的,以前总是拿来主义,现在分享一下让我也为大家做一点贡献好了.废话不说了,看效果. 好吧 其实没什么技术含量 直接上代码好了 和我 ...

  6. 浅谈前端实现页面加载进度条以及 nprogress.js 的实现

    以前在 Vue 的项目用了 nprogress 这个插件,一直对于其如何得知加载进度充满好奇,最近又看到了「前端如何实现页面加载进度条」这个问题,今天周六恰好一探究竟.以下仅为一家之言,如有异议,欢迎 ...

  7. Vue项目实战06:nprogress页面加载进度条

    博客: https://lvsige.top/ nprogress页面加载进度条 前言 很多时候在访问网页的时候我们总是看到页面在加载中,可以却不知道要加载多久,无期限的等待总是让人烦躁不安,所以我们 ...

  8. iview地区加载_LoadingBar 加载进度条

    LoadingBar 加载进度条 概述 全局创建一个显示页面加载.异步请求.文件上传等的加载进度条. 说明 LoadingBar 只会在全局创建一个,因此在任何位置调用的方法都会控制这同一个组件.主要 ...

  9. 【原生JS插件】LoadingBar页面顶部加载进度条

    先展示一下已经实现的效果: 预览地址:http://dtdxrk.github.io/js-plug/LoadingBar/index.html 看到手机上的浏览器内置了页面的加载进度条,想用在pc上 ...

最新文章

  1. 5折交叉验证_[Machine Learning] 模型评估——交叉验证/K折交叉验证
  2. ORACLE 中极易混淆的几个 NAME 的分析和总结
  3. python 自动记录时间_python自动化之时间
  4. AttributeError系列之:AttributeError: module 'scipy.misc' has no attribute 'imread'报错问题
  5. 使用url参数传递SAP Analytics Cloud filter的一个例子
  6. python16进制转10进制_python 字节串及10进制,16进制相关转换
  7. MySQL—常用SQL语句整理总结
  8. 浅谈SQL Server identity列的操作方法
  9. 实现输入界面适应键盘的显示和隐藏事件
  10. 光纤非线性效应对光OFDM信号的影响研究
  11. 基于JavaWeb的果蔬生鲜交易系统
  12. python实现千牛客服自动回复语_千牛客服自动回复话术
  13. int类型和Integer类型数据的比较
  14. C# 程序集(Assembly)
  15. qq邮件如何设置html阅读,如何得知对方是否已阅读QQ邮件?
  16. 6-5 快速排序的实现
  17. 队列--先进先出的线性表
  18. edgeR/limma/DESeq2差异基因分析→ggplot2作火山图→biomaRt转换ID并注释
  19. 184. 部门工资最高的员工
  20. UDS诊断系列介绍07-2E服务

热门文章

  1. 知识图谱中传统关系抽取方法
  2. Pandas 使用入门
  3. photoshop小结
  4. Python多线程调试
  5. 数据库 user schema sqlserver 关系
  6. python yield 和 return 对比分析
  7. LeetCode简单题之将找到的值乘以2
  8. Centos7 下安装VIM编辑器
  9. 绘制多边形_XDGE_RayMarchine 1- 利用Frag Shader绘制图形
  10. python 读取excel 表格的数据