当前位置: 首页 > 编程日记 > 正文

UIWebView、WKWebView使用详解及性能分析

一、整体介绍

UIWebView自iOS2就有,WKWebView从iOS8才有,毫无疑问WKWebView将逐步取代笨重的UIWebView。通过简单的测试即可发现UIWebView占用过多内存,且内存峰值更是夸张。WKWebView网页加载速度也有提升,但是并不像内存那样提升那么多。下面列举一些其它的优势:

  • 更多的支持HTML5的特性
  • 官方宣称的高达60fps的滚动刷新率以及内置手势
  • Safari相同的JavaScript引擎
  • 将UIWebViewDelegate与UIWebView拆分成了14类与3个协议(官方文档说明)
  • 另外用的比较多的,增加加载进度属性:estimatedProgress

二、UIWebView使用说明

1 举例:简单的使用

UIWebView使用非常简单,可以分为三步,也是最简单的用法,显示网页

复制代码
- (void)simpleExampleTest {// 1.创建webview,并设置大小,"20"为状态栏高度UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];// 2.创建请求NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];// 3.加载网页[webView loadRequest:request];// 最后将webView添加到界面[self.view addSubview:webView];
}
复制代码

2 一些实用函数

  • 加载函数。
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;

UIWebView不仅可以加载HTML页面,还支持pdf、word、txt、各种图片等等的显示。下面以加载mac桌面上的png图片:/Users/coohua/Desktop/bigIcon.png为例

// 1.获取url
NSURL *url = [NSURL fileURLWithPath:@"/Users/coohua/Desktop/bigIcon.png"];
// 2.创建请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// 3.加载请求
[self.webView loadRequest:request];
  • 网页导航刷新有关函数
复制代码
// 刷新
- (void)reload;
// 停止加载
- (void)stopLoading;
// 后退函数
- (void)goBack;
// 前进函数
- (void)goForward;
// 是否可以后退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
// 是否可以向前
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
// 是否正在加载
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
复制代码

3 代理协议使用:UIWebViewDelegate

一共有四个方法

复制代码
/// 是否允许加载网页,也可获取js要打开的url,通过截取此url可与js交互
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {NSString *urlString = [[request URL] absoluteString];urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);return YES;
}
/// 开始加载网页
- (void)webViewDidStartLoad:(UIWebView *)webView {NSURLRequest *request = webView.request;NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]);
}
/// 网页加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {NSURLRequest *request = webView.request;NSURL *url = [request URL];if ([url.path isEqualToString:@"/normal.html"]) {NSLog(@"isEqualToString");}NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);NSLog(@"%@",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
}
/// 网页加载错误
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {NSURLRequest *request = webView.request;NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);}
复制代码

4 与js交互

主要有两方面:js执行OC代码、oc调取写好的js代码

  • js执行OC代码:js是不能执行oc代码的,但是可以变相的执行,js可以将要执行的操作封装到网络请求里面,然后oc拦截这个请求,获取url里面的字符串解析即可,这里用到代理协议的- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType函数。
  • oc调取写好的js代码:这里用到UIwebview的一个方法。示例代码一个是网页定位,一个是获取网页title:
复制代码
// 实现自动定位js代码, htmlLocationID为定位的位置(由js开发人员给出),实现自动定位代码,应该在网页加载完成之后再调用
NSString *javascriptStr = [NSString stringWithFormat:@"window.location.href = '#%@'",htmlLocationID];
// webview执行代码
[self.webView stringByEvaluatingJavaScriptFromString:javascriptStr];// 获取网页的title
NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]
复制代码

三、WKWebView使用说明

1 简单使用

与UIWebview一样,仅需三步:记住导入(#import <WebKit/WebKit.h>)

复制代码
- (void)simpleExampleTest {// 1.创建webview,并设置大小,"20"为状态栏高度WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];// 2.创建请求NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];// 3.加载网页[webView loadRequest:request];// 最后将webView添加到界面[self.view addSubview:webView];
}
复制代码

 

2 一些实用函数

  • 加载网页函数
    相比UIWebview,WKWebView也支持各种文件格式,并新增了loadFileURL函数,顾名思义加载本地文件。
复制代码
/// 模拟器调试加载mac本地文件
- (void)loadLocalFile {// 1.创建webview,并设置大小,"20"为状态栏高度WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];// 2.创建url  userName:电脑用户名NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];// 3.加载文件[webView loadFileURL:url allowingReadAccessToURL:url];// 最后将webView添加到界面[self.view addSubview:webView];
}
复制代码

/// 其它三个加载函数
- (WKNavigation *)loadRequest:(NSURLRequest *)request;
- (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL;
  • 网页导航刷新相关函数
    和UIWebview几乎一样,不同的是有返回值,WKNavigation(已更新),另外增加了函数reloadFromOrigingoToBackForwardListItem
    • reloadFromOrigin会比较网络数据是否有变化,没有变化则使用缓存,否则从新请求。
    • goToBackForwardListItem:比向前向后更强大,可以跳转到某个指定历史页面
复制代码
@property (nonatomic, readonly) BOOL canGoBack;
@property (nonatomic, readonly) BOOL canGoForward;
- (WKNavigation *)goBack;
- (WKNavigation *)goForward;
- (WKNavigation *)reload;
- (WKNavigation *)reloadFromOrigin; // 增加的函数
- (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item; // 增加的函数
- (void)stopLoading;
复制代码

 
  • 一些常用属性
    • allowsBackForwardNavigationGestures:BOOL类型,是否允许左右划手势导航,默认不允许
    • estimatedProgress:加载进度,取值范围0~1
    • title:页面title
    • .scrollView.scrollEnabled:是否允许上下滚动,默认允许
    • backForwardList:WKBackForwardList类型,访问历史列表,可以通过前进后退按钮访问,或者通过goToBackForwardListItem函数跳到指定页面

3 代理协议使用

一共有三个代理协议:

  • WKNavigationDelegate:最常用,和UIWebViewDelegate功能类似,追踪加载过程,有是否允许加载、开始加载、加载完成、加载失败。下面会对函数做简单的说明,并用数字标出调用的先后次序:1-2-3-4-5

三个是否允许加载函数:

复制代码
/// 接收到服务器跳转请求之后调用 (服务器端redirect),不一定调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation; 
/// 3 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
/// 1 在发送请求之前,决定是否跳转 
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
复制代码

 

追踪加载过程函数:

复制代码
/// 2 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
/// 4 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
/// 5 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
/// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
复制代码
  • WKScriptMessageHandler:必须实现的函数,是APP与js交互,提供从网页中收消息的回调方法
/// message: 收到的脚本信息.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;

 
  • WKUIDelegate:UI界面相关,原生控件支持,三种提示框:输入、确认、警告。首先将web提示框拦截然后再做处理。
复制代码
/// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
/// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
/// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
/// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
复制代码

四、示例代码

  • 代码可以实现一般网络显示,加载本地文件(pdf、word、txt、图片等等)
  • 搜索框搜索界面,搜索框输入file://则加载本地文件,http://则加载网络内容,如果两者都不是则搜索输入的关键字。
  • 下部网络导航,后退、前进、刷新、用Safari打开链接四个按钮

主界面——简述主页
复制代码
/// 控件高度
#define kSearchBarH  44
#define kBottomViewH 44/// 屏幕大小尺寸
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height#import "ViewController.h"
#import <WebKit/WebKit.h>@interface ViewController () <UISearchBarDelegate, WKNavigationDelegate>@property (nonatomic, strong) UISearchBar *searchBar;
/// 网页控制导航栏
@property (weak, nonatomic) UIView *bottomView;@property (nonatomic, strong) WKWebView *wkWebView;@property (weak, nonatomic) UIButton *backBtn;
@property (weak, nonatomic) UIButton *forwardBtn;
@property (weak, nonatomic) UIButton *reloadBtn;
@property (weak, nonatomic) UIButton *browserBtn;@property (weak, nonatomic) NSString *baseURLString;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];
//    [self simpleExampleTest];[self addSubViews];[self refreshBottomButtonState];[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]];}
- (void)simpleExampleTest {// 1.创建webview,并设置大小,"20"为状态栏高度WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];// 2.创建请求NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
//    // 3.加载网页[webView loadRequest:request];
//    [webView loadFileURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"] allowingReadAccessToURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]];// 最后将webView添加到界面[self.view addSubview:webView];
}
/// 模拟器加载mac本地文件
- (void)loadLocalFile {// 1.创建webview,并设置大小,"20"为状态栏高度WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];// 2.创建url  userName:电脑用户名NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];// 3.加载文件[webView loadFileURL:url allowingReadAccessToURL:url];// 最后将webView添加到界面[self.view addSubview:webView];
}
- (void)addSubViews {[self addBottomViewButtons];[self.view addSubview:self.searchBar];[self.view addSubview:self.wkWebView];
}- (void)addBottomViewButtons {// 记录按钮个数int count = 0;// 添加按钮UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];[button setTitle:@"后退" forState:UIControlStateNormal];[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];[button.titleLabel setFont:[UIFont systemFontOfSize:15]];button.tag = ++count;    // 标记按钮[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];[self.bottomView addSubview:button];self.backBtn = button;button = [UIButton buttonWithType:UIButtonTypeCustom];[button setTitle:@"前进" forState:UIControlStateNormal];[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];[button.titleLabel setFont:[UIFont systemFontOfSize:15]];button.tag = ++count;[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];[self.bottomView addSubview:button];self.forwardBtn = button;button = [UIButton buttonWithType:UIButtonTypeCustom];[button setTitle:@"重新加载" forState:UIControlStateNormal];[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];[button.titleLabel setFont:[UIFont systemFontOfSize:15]];button.tag = ++count;[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];[self.bottomView addSubview:button];self.reloadBtn = button;button = [UIButton buttonWithType:UIButtonTypeCustom];[button setTitle:@"Safari" forState:UIControlStateNormal];[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];[button.titleLabel setFont:[UIFont systemFontOfSize:15]];button.tag = ++count;[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];[self.bottomView addSubview:button];self.browserBtn = button;// 统一设置frame[self setupBottomViewLayout];
}
- (void)setupBottomViewLayout
{int count = 4;CGFloat btnW = 80;CGFloat btnH = 30;CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2;// 按钮间间隙CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count;CGFloat btnX = margin * 0.5;self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);btnX = self.backBtn.frame.origin.x + btnW + margin;self.forwardBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);btnX = self.forwardBtn.frame.origin.x + btnW + margin;self.reloadBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);btnX = self.reloadBtn.frame.origin.x + btnW + margin;self.browserBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
/// 刷新按钮是否允许点击
- (void)refreshBottomButtonState {if ([self.wkWebView canGoBack]) {self.backBtn.enabled = YES;} else {self.backBtn.enabled = NO;}if ([self.wkWebView canGoForward]) {self.forwardBtn.enabled = YES;} else {self.forwardBtn.enabled = NO;}
}
/// 按钮点击事件
- (void)onBottomButtonsClicled:(UIButton *)sender {switch (sender.tag) {case 1:{[self.wkWebView goBack];[self refreshBottomButtonState];}break;case 2:{[self.wkWebView goForward];[self refreshBottomButtonState];}break;case 3:[self.wkWebView reload];break;case 4:[[UIApplication sharedApplication] openURL:self.wkWebView.URL];break;default:break;}
}#pragma mark - WKWebView WKNavigationDelegate 相关
/// 是否允许加载网页 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {NSString *urlString = [[navigationAction.request URL] absoluteString];urlString = [urlString stringByRemovingPercentEncoding];//    NSLog(@"urlString=%@",urlString);// 用://截取字符串NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];if ([urlComps count]) {// 获取协议头NSString *protocolHead = [urlComps objectAtIndex:0];NSLog(@"protocolHead=%@",protocolHead);}decisionHandler(WKNavigationActionPolicyAllow);
}#pragma mark - searchBar代理方法
/// 点击搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {// 创建urlNSURL *url = nil;NSString *urlStr = searchBar.text;// 如果file://则为打开bundle本地文件,http则为网站,否则只是一般搜索关键字if([urlStr hasPrefix:@"file://"]){NSRange range = [urlStr rangeOfString:@"file://"];NSString *fileName = [urlStr substringFromIndex:range.length];url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];// 如果是模拟器加载电脑上的文件,则用下面的代码
//        url = [NSURL fileURLWithPath:fileName];}else if(urlStr.length>0){if ([urlStr hasPrefix:@"http://"]) {url=[NSURL URLWithString:urlStr];} else {urlStr=[NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@",urlStr];}urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];url=[NSURL URLWithString:urlStr];}NSURLRequest *request=[NSURLRequest requestWithURL:url];// 加载请求页面[self.wkWebView loadRequest:request];
}
#pragma mark - 懒加载
- (UIView *)bottomView {if (_bottomView == nil) {UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];[self.view addSubview:view];_bottomView = view;}return _bottomView;
}
- (UISearchBar *)searchBar {if (_searchBar == nil) {UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kSearchBarH)];searchBar.delegate = self;searchBar.text = @"http://www.cnblogs.com/mddblog/";_searchBar = searchBar;}return _searchBar;
}- (WKWebView *)wkWebView {if (_wkWebView == nil) {WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20 + kSearchBarH, kScreenWidth, kScreenHeight - 20 - kSearchBarH - kBottomViewH)];webView.navigationDelegate = self;
//                webView.scrollView.scrollEnabled = NO;//        webView.backgroundColor = [UIColor colorWithPatternImage:self.image];// 允许左右划手势导航,默认允许webView.allowsBackForwardNavigationGestures = YES;_wkWebView = webView;}return _wkWebView;
}@end
复制代码

五、UIWebView 和 WKWebView的性能分析

iOS 8 推出 WKWebView 以及相关特性,告诉开发者提高多么多么大的性能,实测告诉你WKWebView的性能有多好!

为了验证,我在项目中的分别 使用UIWebView 和 WKWebView 测试,来回加载十多个网页 产生的内存状况如下:

UIWebView

id="iframe_0.9264127238737117" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1977807-1ffff25f6c22e563.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.9264127238737117" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
WKWebView
id="iframe_0.2527370225042682" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1977807-44c1ddd0c0299195.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.2527370225042682" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">

对比发现 WKWebview 这货 在persistent 常驻内存 使用得少多了,想想看,一个app去哪儿省下几十M的内存,再加上用户量分布
iOS 9 60%
iOS 8 30%
iOS 7 6%左右
所以我建议能换WKWebview 就换吧,省下一大块内存减少不必要的异常bug。

iOSH5性能监控技术角度分析

性能数据了解

分析移动端H5性能数据,首先我们说说是哪些性能数据。

  • 白屏时间,白屏时间无论安卓还是iOS在加载网页的时候都会存在的问题,也是目前无法解决的;
  • 页面耗时,页面耗时指的是开始加载这个网页到整个页面load完成即渲染完成的时间;
  • 加载链接的一些性能数据,重定向时间,DNS解析时间,TCP链接时间,request请求时间,response响应时间,dom节点解析时间,page渲染时间,同时我们还需要抓取资源时序数据,

什么是资源时序数据呢?每个网页是有很多个资源组成的,有.js、.png、.css、.script等等,我们就需要将这些每个资源链接的耗时拿到,是什么类型的资源,完整链接;对于客户来说有了这些还不够,还需要JS错误,页面的ajax请求。JS错误获取的当然是堆栈信息和错误类型。ajax请求一般是获取三个时间,响应时间,ajax下载时间,ajax回调时间。

上面分析的是能够获取到移动端H5的性能数据,这些数据怎么得到就是接下来要讲的了。数据获取是需要js来做的,都知道移动端是通过webView来加载网页的,js里面能通过performance这个接口来从webView内部api获取上面的那些数据,js获取的数据然后发给OC;那JS怎么样才能拿到这些数据呢,这就是最关键的,OC代码如何写才能让JS获取数据。

代码编写

有两种方法可以得到数据,先介绍用NSURLProtocol这个类获取数据。

iOS的UIWebView加载网页的时候会走进NSURLProtocol这个类,所以我们就需要在这个类里面作文章了,我们先用UIWebView加载一个链接,例如百度等等,然后创建一个继承NSURLProtocol的类。

id="iframe_0.6359781224071638" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-5b2121c66e9972a6.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.6359781224071638" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
继承NSURLProtocol

NSURLProtocol里面有很多方法,就不一一介绍了,有一个startLoading的方法,我们在这个方法里面用NSURLConnection发送一个请求,设置代理,请求的request就是加载网页的request,因为NSURLProtocol有一个NSURLRequest的属性。

- (instancetype)initWithRequest:(NSURLRequest*)request delegate:(id)delegate startImmediately:(BOOL)startImmediately

这个就是请求的方法。

id="iframe_0.20530720466165608" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-bdfac347a23e459e.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.20530720466165608" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
发送请求

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

通过NSURLConnection设置代理,就需要写出代理方法,在其中一个代理方法里面能获得网页的代码,这就是我们最关键的地方,就是上面这个方法,将data用utf-8转码就会得到代码。

id="iframe_0.36887266657903195" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-4e127f0607d1a9b6.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.36887266657903195" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
插入js代码的方法

得到网页的代码有什么用呢?熟悉网页端代码的都知道,网页端的代码都是由很多标签组成,我们先找到<head>这个标签,在下面插入一个<script>标签,里面放入js代码,这个js代码就是用来获取上面介绍的性能数据。

- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;

上面会用到很多这个方法,为什么要用这个呢,因为你注入了新的代码,你需要将这个新的网页代码用这个方法加载一下,不然网页会加载不出来的。

最后只需要将MonitorURLProtocol在appDelegate里面注册一下就可以了。

id="iframe_0.7120613315883303" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-06655b0eadcae845.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.7120613315883303" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
注册创建的类

以上是通过NSURLProtocol这个类注入获取数据的代码,将JS代码注入后就需要JS将数据发送给我们,可以通过交互这些方式,接下来我就介绍一种直白的交互,大多数的交互也是这么做的,只不过封装了,考虑的情况更多,我就只是根据实际情况来做了。

OC与JS交互获取数据

交互都会有一个标识,OC传一个标识给JS,JS通过标识判断,发送给你想要的数据。我首先是通过运行时动态加载的方法将加载链接的三个方法给hook,进入同一个我定义的方法,然后在这个方法里面传标识给JS。

id="iframe_0.5556481639006317" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-e73bcbc2e06efa9f.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.5556481639006317" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
hook
id="iframe_0.22053100136326442" src="https://www.cnblogs.com/show-blocking-image.aspx?url=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1744191-6deb4e11ef0acf3d.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&maxWidth=753&origin=http://www.cnblogs.com&iframeId=iframe_0.22053100136326442" style="border-width: medium; border-style: none; width: 753px;" scrolling="no" frameborder="0">
数据获取

将标识和block作为键值对存起来,然后将JS将数据用url的形式发过来,我们取出来,匹配一下对应相应的标识,然后用block回调相应的数据,相应的代码这里就不贴了,最后我会给github上代码的链接。接受url就是用UIWebView的代理方法。

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

{

[WebViewTracker webView:webView withUrl:request.URL];

return YES;

}

我们还可以在didFinishLoad里面手动调用JS代码来获取获取数据,和NSURLProtocol结合起来用,各有各的优缺点,一个是在顶部注入代码,一个是在尾部调用代码,都是会丢失一部分数据,所以最好的办法就是结合起来用。

以上是自己获取这些数据,如果是做成SDK监控APP获取这些数据,就不一样了,需要去hookUIWebView的代理方法,hook静态库的方法和普通的运行时加载是不一样的,这个我可以在以后的文章里面介绍。

WKWebView

WKWebView是iOS8.0以后出来的,目前使用的人还不是很多,但是这个比UIWebView性能方面好很多,从内核到内存优化等等,但是由于还有iOS7以下的用户,所以面使用的人不多,但是这个是趋势。WKWebView获取上面的性能数据是一模一样的,不同的是WKWebView不会走进NSURLProtocol,所以实在didFinishLoad里面手动调用

相关文章:

FFmpeg中libavutil库简介及测试代码

libavutil是一个实用库&#xff0c;用于辅助多媒体编程。此库包含安全的可移植字符串函数、随机数生成器、数据结构、附加数学函数、加密和多媒体相关功能(如像素和样本格式的枚举)。libavcodec和libavformat并不依赖此库。 以下是测试代码&#xff0c;包括base64, aes, des, …

区块链人才月均薪酬1.6万元?

在上周&#xff0c;我国宣布将重点推动区块链技术的发展&#xff0c;这个消息无疑是为区块链开发者们打了一直强心剂&#xff0c;简直是喜大普奔啊 &#xff01; 因为之前区块链这个技术虽然一直在圈内很火&#xff0c;但是却没有得到国家的全面认可和推广&#xff0c;所以很多…

用最少的时间学最多的数据挖掘知识(附教程数据源)| CSDN博文精选

作者 | 宋莹来源 | 数据派THU&#xff08;ID:DatapiTHU&#xff09;本文为你介绍数据挖掘的知识及应用。引言最近笔者学到了一个新词&#xff0c;叫做“认知折叠”。就是将复杂的事物包装成最简单的样子&#xff0c;让大家不用关心里面的细节就能方便使用。作为数据科学领域从业…

WKWebView 的使用简介

1. navigationDelegate [objc] view plaincopy print?- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // 类似UIWebView的 -webViewDidStartLoad: NSLog("didStartProvisionalNavigation"); [UIAppli…

FFmpeg中libswscale库简介及测试代码

libswscale库功能主要包括高度优化的图像缩放、颜色空间和像素格式转换操作。 以下是测试代码(test_ffmpeg_libswscale.cpp)&#xff1a; #include "funset.hpp" #include <string.h> #include <iostream> #include <string> #include <memor…

FFmpeg中libswresample库简介及测试代码

libswresample库功能主要包括高度优化的音频重采样、rematrixing和样本格式转换操作。 以下是测试代码(test_ffmpeg_libswresample.cpp)&#xff0c;对音频了解较少&#xff0c;测试代码是参考examples中的&#xff1a; #include "funset.hpp" #include <iostre…

高德地图POI搜索,附近地图搜索,类似附近的人搜索

效果图&#xff1a; 首先导入道德地图的SDK&#xff0c;导入步骤不在这里介绍 2&#xff1a;包含头文件&#xff1a; [objc] view plaincopy #import <AMapSearchKit/AMapSearchAPI.h> 3&#xff1a;代码 [javascript] view plaincopy property(nonatomic,strong)AMap…

手把手教你实现PySpark机器学习项目——回归算法

作者 | hecongqing 来源 | AI算法之心&#xff08;ID:AIHeartForYou&#xff09;【导读】PySpark作为工业界常用于处理大数据以及分布式计算的工具&#xff0c;特别是在算法建模时起到了非常大的作用。PySpark如何建模呢&#xff1f;这篇文章手把手带你入门PySpark&#xff0c;…

mcDropdown使用方法

最近使用了mcDropdown插件&#xff0c;百度一查&#xff0c;资料较少&#xff0c;只看到了mcDropdown官网的英文说明文档&#xff0c;所以今天就写点&#xff0c;以便以后使用。 第一步&#xff1a;引用jquery库和css jQuery v1.2.6 (or higher)*jquery.mcdropdown.js Plug-inj…

Windows上通过VLC播放器搭建rtsp流媒体测试地址操作步骤

1. 从https://www.videolan.org/index.zh.html 下载最新的windows 64bit 3.0.6版本并安装&#xff1b; 2. 打开VLC media player&#xff0c;依次点击按钮&#xff1a;”媒体” --> “流”&#xff0c;如下图所示&#xff1a; 3. 点击”添加”按钮&#xff0c;选择一个视频…

Swift - AppDelegate.swift类中默认方法的介绍

项目创建后&#xff0c;AppDelegate类中默认带有如下几个方法&#xff0c;具体功能如下&#xff1a; 1&#xff0c;应用程序第一次运行时执行这个方法只有在App第一次运行的时候被执行过一次&#xff0c;每次App从后台激活时都不会再执行该方法。&#xff08;注&#xff1a;所有…

上热搜了!“学了Python6个月,竟然找不到工作!”

在编程界&#xff0c;Python是一种神奇的存在。有人认为&#xff0c;只有用Python才能优雅写代码&#xff0c;提高代码效率&#xff1b;但另一部分人恨不能把Python喷成筛子。那么&#xff0c;Python到底有没有用&#xff0c;为什么用Python找不到工作&#xff1f;CSDN小姐姐带…

Linux0.00内核为什么要自己设置0x80号陷阱门来调用write_char过程?

我一开始没注意这个问题&#xff0c;只是通过陷阱门觉得很绕弯子&#xff0c;为何不在3级用户代码里直接调用write_char&#xff0c;今天自己写程序想用call调用代码段&#xff0c;才发现了大问题。我写了个类似于write_char的过程&#xff0c;代码如下&#xff1a;dividing_li…

iOS支付宝(Alipay)接入详细流程,比微信支付更简单,项目实战中的问题分析

最近在项目中接入了微信支付和支付宝支付&#xff0c;总的来说没有那么坑&#xff0c;很多人都说文档不全什么的&#xff0c;确实没有面面 俱到&#xff0c;但是认真一步一步测试下还是妥妥的&#xff0c;再配合懂得后台&#xff0c;效率也是很高的&#xff0c;看了这篇文章&a…

LIVE555简介及在Windows上通过VS2013编译操作步骤

LIVE555是使用开放标准协议(RTP/RTCP, RTSP, SIP)形成的一组用于多媒体流C库。这些库支持的平台包括Unix(包括Linux和Mac OS X)、Windows和QNX(以及其它符号POSIX的系统)。这些库已经被用于实现的应用例如LIVE555媒体服务器、LIVE555代理服务器(RTSP服务器应用)以及vobStreamer…

GitHub App终于来了,iPhone用户可尝鲜,「同性交友」更加便捷

整理 | 夕颜出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】据外媒 VentureBeat 报道&#xff0c;在 11 月 13 日举行的 GitHub Universe 上&#xff0c;微软宣布了面向程序员和开发人员的一系列升级&#xff0c;包括针对 iOS 智能手机和 iPad 推出的 GitHub…

[NHibernate]代码生成器的使用

目录 写在前面 文档与系列文章 代码生成器的使用 总结 写在前面 前面的文章介绍了nhibernate的相关知识&#xff0c;都是自己手敲的代码&#xff0c;有时候显得特别的麻烦&#xff0c;比如你必须编写持久化类&#xff0c;映射文件等等&#xff0c;举得例子比较简单&#xff0c;…

RapidJSON简介及使用

RapidJSON是腾讯开源的一个高效的C JSON解析器及生成器&#xff0c;它是只有头文件的C库。RapidJSON是跨平台的&#xff0c;支持Windows, Linux, Mac OS X及iOS, Android。它的源码在https://github.com/Tencent/rapidjson/&#xff0c;稳定版本为2016年发布的1.1.0版本。 Rap…

高德地图关键字搜索oc版

.h文件 // MapSearchViewController.h // JMT // // Created by walker on 16/10/11. // Copyright © 2016年 BOOTCAMP. All rights reserved. // #import <UIKit/UIKit.h> #import <AMapNaviKit/MaMapKit.h> #import <AMapSearchKit/AMapSearchKit.h&…

同一个内容,对比Java、C、PHP、Python的代码量,结局意外了

为什么都说Python容易上手&#xff01;是真的吗&#xff1f;都说Python通俗易懂&#xff0c;容易上手&#xff0c;甚至不少网友表示「完成同一个任务&#xff0c;C 语言要写 1000 行代码&#xff0c;Java 只需要写 100 行&#xff0c;而 Python 可能只要 20 行」到底是真的还是…

图片存储思考:

http://blog.csdn.net/liuruhong/article/details/4072386

LIVE555中RTSP客户端接收媒体流分析及测试代码

LIVE555中testProgs目录下的testRTSPClient.cpp代码用于测试接收RTSP URL指定的媒体流&#xff0c;向服务器端发送的命令包括&#xff1a;DESCRIBE、SETUP、PLAY、TERADOWN。 1. 设置使用环境&#xff1a;new一个BasicTaskScheduler对象&#xff1b;new一个BasicUsageEnvironm…

swift代理传值

比如我们这个场景&#xff0c;B要给A传值&#xff0c;那B就拥有代理属性&#xff0c; A就是B的代理&#xff0c;很简单吧&#xff01;有代理那就离不开协议&#xff0c;所以第一步就是声明协议。在那里声明了&#xff1f;谁拥有代理属性就在那里声明&#xff0c;所以代码就是这…

重磅:腾讯正式开源图计算框架Plato,十亿级节点图计算进入分钟级时代

整理 | 唐小引 来源 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09;腾讯开源进化 8 年&#xff0c;进入爆发期。 继刚刚连续开源 TubeMQ、Tencent Kona JDK、TBase、TKEStack 四款重点开源项目后&#xff0c;腾讯开源再次迎来重磅项目&#xff01;北京时间 11 月 14 日…

类似ngnix的多进程监听用例

2019独角兽企业重金招聘Python工程师标准>>> 多进程监听适合于短连接&#xff0c;且连接间无交集的应用。前两天简单写了一个&#xff0c;在这里保存一下。 #include <sys/types.h>#include <stdarg.h>#include <signal.h>#include <unistd.h&…

今日头条李磊等最新论文:用于文本生成的核化贝叶斯Softmax

译者 | Raku 出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;摘要用于文本生成的神经模型需要在解码阶段具有适当词嵌入的softmax层&#xff0c;大多数现有方法采用每个单词单点嵌入的方式&#xff0c;但是一个单词可能具有多种意义&#xff0c;在不同的背景下&#…

FFmpeg中RTSP客户端拉流测试代码

之前在https://blog.csdn.net/fengbingchun/article/details/91355410中给出了通过LIVE555实现拉流的测试代码&#xff0c;这里通过FFmpeg来实现&#xff0c;代码量远小于LIVE555&#xff0c;实现模块在libavformat。 在4.0及以上版本中&#xff0c;FFmpeg有了些变动&#xff…

虚拟机下运行linux通过nat模式与主机通信、与外网连接

首先&#xff1a;打开虚拟机的编辑菜单下的虚拟网络编辑器&#xff0c;选中VMnet8 NAT模式。通过NAT设置获取网关IP&#xff0c;通过DHCP获取可配置的IP区间。同时&#xff0c;将虚拟机的虚拟机菜单的设置选项中的网络适配器改为NAT模式。即可&#xff01; 打开linux&#xff0…

远程过程调用RPC简介

RPC(Remote Procedure Call, 远程过程调用)&#xff1a;是一种通过网络从远程计算机程序上请求服务&#xff0c;而不需要了解底层网络技术的思想。 RPC是一种技术思想而非一种规范或协议&#xff0c;常见RPC技术和框架有&#xff1a; (1). 应用级的服务框架&#xff1a;阿里的…

iOS开发:沙盒机制以及利用沙盒存储字符串、数组、字典等数据

iOS开发&#xff1a;沙盒机制以及利用沙盒存储字符串、数组、字典等数据 1、初识沙盒&#xff1a;(1)、存储在内存中的数据&#xff0c;程序关闭&#xff0c;内存释放&#xff0c;数据就会丢失&#xff0c;这种数据是临时的。要想数据永久保存&#xff0c;将数据保存成文件&am…