在开发过程中,iOS 中实现加载 web 页面主要有两种控件,UIWebView 和 WKWebview,两种控件对应具体的实现方法不同。WKWebView是苹果公司在iOS8系统推出的,这里主要概述WebKit中更新的WKWebView控件的新特性与使用方法,以及小编在开发过程中踩的坑。

一、相比于UIWebView的优势:

  1. 在性能、稳定性、占用内存方面有很大提升;
  2. 允许JavaScript的Nitro库加载并使用(UIWebView中限制)
  3. 增加加载进度属性:estimatedProgress,不用在自己写假进度条了
  4. 支持了更多的HTML的属性

二、WKWebview的常用属性

@property (nullable, nonatomic, readonly, copy) NSString *title;

@property (nullable, nonatomic, readonly, copy) NSURL *URL;

@property (nonatomic, readonly, getter=isLoading) BOOL loading;
//加载进度
@property (nonatomic, readonly) double estimatedProgress;

三、WKWebview的常用方法

- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;

- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL API_AVAILABLE(macosx(10.11), ios(9.0));

- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;

- (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL API_AVAILABLE(macosx(10.11), ios(9.0));

四、WKNavigationDelegate代理的方法

#pragma mark - WKNavigationDelegate
/* 页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"页面开始加载");
}
/* 开始返回内容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
NSLog(@"开始返回内容");
}
/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSLog(@"页面加载完成");
}
/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"页面加载失败");
}
/* 在发送请求之前,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到响应后,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{ NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//允许跳转
decisionHandler(WKNavigationResponsePolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationResponsePolicyCancel);
}

五、小编的实例Demo

首先遵守协议:

<WKUIDelegate, WKNavigationDelegate>

其次创建一个WKWebView

#pragma mark - 创建webView
- (void)createWebView{ WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.selectionGranularity = WKSelectionGranularityDynamic;
config.allowsInlineMediaPlayback = YES;
WKPreferences *preferences = [WKPreferences new];
//是否支持JavaScript
preferences.javaScriptEnabled = YES;
//不通过用户交互,是否可以打开窗口
preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.preferences = preferences;
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.webView]; /* 加载服务器url的方法*/
NSString *url = @"https://www.baidu.com";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[self.webView loadRequest:request]; self.webView.navigationDelegate = self;
self.webView.UIDelegate = self; }

这样就可以在webView中正常加载百度首页了。

不过,在开发中有时遇到网络不佳的时候,想给用户显示一个加载网页的进度,加载完成后,想再navigation中显示网页的标题,就需要对WKWebView的"estimatedProgress"和

"title"进行监听了。

首先创建一个进度条

- (void)createProgressView{
self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(, , SCREEN_WIDTH, )];
self.progressView.progressViewStyle = UIProgressViewStyleDefault;
self.progressView.tintColor = [UIColor blueColor];
self.progressView.trackTintColor = [UIColor greenColor];
[self.view addSubview:self.progressView];
}

让webView对“进度”和“标题”进行监听

[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

最后,完成对KVO的回调

#pragma mark - KVO回馈
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
double progress = _webView.estimatedProgress;
self.progressView.alpha = 1.0f;
[self.progressView setProgress:progress animated:YES];
if(progress >= ){
[UIView animateWithDuration:0.25 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
self.progressView.alpha = 0.0f;
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
return;
}
if ([change[@"new"]floatValue] == 1.0) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(. * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ });
}
}
else if ([keyPath isEqualToString:@"title"]){
self.title = change[@"new"];
}
}

这样就实现了对加载进度的显示了。

WKWebview的基本使用的更多相关文章

  1. WKWebView浅析

    原文链接:supermokey WKWebView 一个WKWebView对象展示交互的web内容,例如应用于app内的浏览器.你可以在你的App中使用WKWebView. 综述 Important: ...

  2. iOS网络3—UIWebView与WKWebView使用详解

    一.整体介绍 UIWebView自iOS2就有,WKWebView从iOS8才有,毫无疑问WKWebView将逐步取代笨重的UIWebView.通过简单的测试即可发现UIWebView占用过多内存,且 ...

  3. WKWebView与JavaScript交互基础

    login.html 代码 <!DOCTYPE html> <html> <head> <title>使用JavaScript</title> ...

  4. IOS进阶之WKWebView

    前言 Xcode8发布以后,编译器开始不支持IOS7,所以很多应用在适配IOS10之后都不在适配IOS7了,其中包括了很多大公司,网易新闻,滴滴出行等.因此,我们公司的应用也打算淘汰IOS7. 支持到 ...

  5. iOS 开发之路(WKWebView内嵌HTML5之图片上传) 五

    HTML5页面的图片上传功能在iOS端的实现. 首先,页面上用的是plupload组件,在wkwebview上存在两个坑需要修复才能正常使用. 问题:在webview上点击选择照片/相机拍摄,就会出现 ...

  6. WKWebView与JS交互,UIWebView+JavascriptCore和JS交互

    最近一直在做有关Swift和JavaScript交互的程序,所以有关UIWebView和WKWebView在使用上的差别在此总结下: UIWebView: (1)创建 var webView: UIW ...

  7. iOS WKWebView的javascript alert 不弹的解决方案

    - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiate ...

  8. 使用WKWebView遇到的坑

    苹果从iOS8开始推出了WKWebView,大有替换UIWebView的意思(尽管Xcode中还没给UIWebView标记过期版本),所以决定将项目进行适配,iOS8及以上版本,改用WKWebView ...

  9. [原创]WKWebview点击图片查看大图

    大家都知道,WKWebview是没有查看大图的属性或者方法的,所以只能通过js与之交互来实现这一功能,原理:通过js获取页面的图片,把它存放到数组,给图片添加点击事件,通过index显示大图就行了 其 ...

  10. WKWebView

    按错了...,原帖地址http://blog.csdn.net/cyforce/article/details/37657009 webkit使用WKWebView来代替IOS的UIWebView和O ...

随机推荐

  1. Android 最新L版本,都更新什么东西了

    Android L版本重大修改 一:New Android Runtime (ART) 新的运行环境,4.4一下的版本ART是可选的运行环境,默认还是Dalvik.但是在Android L版本之后默认 ...

  2. iOS --发送手机验证码收不到手机验证码

    方法一:使用受信任设备上显示的验证码. 如果您的受信任设备是iOS 9 及以上系统时,则验证码将自动显示在受信任设备上.此时你信任的设备上会弹出你在某地登录ID位置的小地图,有一个选择允许与不允许登录 ...

  3. 《TP5.0学习笔记---配置篇》

    参考博客:http://blog.csdn.net/self_realian/article/details/75045541

  4. The server encountered an internal error that prevented it from fulfilling this request.(JsonMappingException: Conflicting getter definitions)

    在测试一个方法,dubug查看查询结果已经出来了,结果页面上是The server encountered an internal error that prevented it from fulfi ...

  5. LeetCode Problem 35:Search Insert Position

    描述:Given a sorted array and a target value, return the index if the target is found. If not, return ...

  6. tomcat开启远程调试

    tomcat开启远程调试模式: 需要在启动脚本中的 JAVA_OPTS='-server -Xms1024m -Xmx1024m -Xmn384m -Xss256k -XX:PermSize=128m ...

  7. IDEA : Git Pull Failed 解决(IDEA中使用stash功能)

    一.问题: 本地要commit代码,commit之前需pull代码,但pull提示冲突.如下 Git Pull Failed Your local changes would be overwritt ...

  8. FlaskWeb开发

    Flask基本使用 上下文 程序上下文 current_app g 请求上下文 request session https://blog.csdn.net/wsxqaz/article/details ...

  9. maven 打包报错

    [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------ ...

  10. js引入方式的弹框方法2

    html代码: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv=& ...