一、整体介绍

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(, , self.view.frame.size.width, self.view.frame.size.height - )];
// 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"];
  • 与js交互的实例

很多时候,我们要对网页做一些编辑,比如加载一个网页后,个别原因,我们不想显示新闻的来源,如下图的新闻来源“新华网”,网页的链接如下:http://op.inews.qq.com/mcms/h5/default/detail?id=NEW2016103101306200&refer=100000050(可能已经失效)

那我们就可以使用js代码将这个标签去掉,且只留下时间。js代码的编写,根据火狐浏览器查看它的标签名称,然后做处理,如上图,具体代码如下:

- (void)deleteNewsSource {
// 1.去掉页面标题
NSMutableString *str = [NSMutableString string];
// 去掉导航页,如果想把“腾讯新闻”导航栏一并去掉,就打开注释
// [str appendString:@"document.getElementsByClassName('g-header')[0].style.display = 'none';"];
// 来源
[str appendString:@"if(document.getElementsByClassName('g-wrapper-author')[0].innerHTML.indexOf(' ') == -1){document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML}else{document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML.split(' ')[1];}"];
// 执行js代码
[_webView stringByEvaluatingJavaScriptFromString:str];
}

代码执行的时机,一般情况下是等待网页加载完成- (void)webViewDidFinishLoad:(UIWebView *)webView里面执行,比较合理,但是有延迟,我们会发现刚开始有来源,然后突然又没有了,即js代码执行有延迟。

这样的话,我们可以在- (void)webViewDidStartLoad:(UIWebView *)webView网页开始加载里面开启一个定时器,比如定时0.2秒(根据需要自己设定),在定时器里面不停的调用- (void)deleteNewsSource方法即可解决。然后在- (void)webViewDidFinishLoad:(UIWebView *)webView里面关掉定时器。另外定时器容易引起循环引用,一定要注意释放。比如可以在viewDidDisappear方法里释放定时器。。。

- (void)webViewDidStartLoad:(UIWebView *)webView {
// 1.去掉页面来源标签,时间根据需要自己设置,定时器在这里开启具有一定危险性
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(deleteNewsSource) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.timer = timer;
}

三、WKWebView使用说明

1 简单使用

与UIWebview一样,仅需三步:

- (void)simpleExampleTest {
// 1.创建webview,并设置大小,"20"为状态栏高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height - )];
// 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函数,顾名思义加载本地文件,不要用loadRequest来加载本地HTML,另外,加载网页显示属于UI,所以应在主线程里面执行加载网页函数,不过即使在其它线程执行了加载网页函数,也没关系,苹果已做了处理,保证UI在主线程更新。
/// 模拟器调试加载mac本地文件
- (void)loadLocalFile {
// 1.创建webview,并设置大小,"20"为状态栏高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height - )];
// 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函数跳到指定页面
  • 执行js代码

/// jsStr为要执行的js代码,字符串形式
[webView evaluateJavaScript:jsStr completionHandler:^(id item, NSError * _Nullable error) {
// 执行结果回调
}];

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交互,提供从网页中收消息的回调方法,即js可以调用app的方法

当然需要对webview做一些特殊处理,创建的时候调用initWithFrame:configuration:做一些配置,configurationWKWebViewConfiguration类型,具体不再详述,代理方法如下:

/// message: 收到的脚本信息.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
当然,app也可以执行js代码,如下:
/// jsStr为要执行的js代码,字符串形式
[webView evaluateJavaScript:jsStr completionHandler:^(id item, NSError * _Nullable error) {
// 执行结果回调
}];
  • 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(, , self.view.frame.size.width, self.view.frame.size.height - )];
// 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(, , self.view.frame.size.width, self.view.frame.size.height - )];
// 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 = ;
// 添加按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"后退" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed: / 255.0 green: / 255.0 blue: / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:]];
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: / 255.0 green: / 255.0 blue: / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:]];
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: / 255.0 green: / 255.0 blue: / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:]];
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: / 255.0 green: / 255.0 blue: / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:]];
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 = ;
CGFloat btnW = ;
CGFloat btnH = ; CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / ;
// 按钮间间隙
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 :
{
[self.wkWebView goBack];
[self refreshBottomButtonState];
}
break;
case :
{
[self.wkWebView goForward];
[self refreshBottomButtonState];
}
break;
case :
[self.wkWebView reload];
break;
case :
[[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:];
NSLog(@"protocolHead=%@",protocolHead);
}
decisionHandler(WKNavigationActionPolicyAllow);
} #pragma mark - searchBar代理方法
/// 点击搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// 创建url
NSURL *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>){
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(, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];
view.backgroundColor = [UIColor colorWithRed:/255.0 green:/255.0 blue:/255.0 alpha:];
[self.view addSubview:view];
_bottomView = view;
}
return _bottomView;
}
- (UISearchBar *)searchBar {
if (_searchBar == nil) {
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(, , 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(, + kSearchBarH, kScreenWidth, kScreenHeight - - kSearchBarH - kBottomViewH)];
webView.navigationDelegate = self;
// webView.scrollView.scrollEnabled = NO; // webView.backgroundColor = [UIColor colorWithPatternImage:self.image];
// 允许左右划手势导航,默认允许
webView.allowsBackForwardNavigationGestures = YES;
_wkWebView = webView;
} return _wkWebView;
} @end

五、github代码下载

UIWebView下载

WKWebView下载

iOS网络3—UIWebView与WKWebView使用详解的更多相关文章

  1. iOS UIWebView与WKWebView使用详解

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

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

    http://www.cnblogs.com/junhuawang/p/5759224.html

  3. 【iOS 使用github上传代码】详解

    [iOS 使用github上传代码]详解 一.github创建新工程 二.直接添加文件 三.通过https 和 SSH 操作两种方式上传工程 3.1https 和 SSH 的区别: 3.1.1.前者可 ...

  4. Linux网络状态工具ss命令使用详解【转】

    ss命令用于显示socket状态. 他可以显示PACKET sockets, TCP sockets, UDP sockets, DCCP sockets, RAW sockets, Unix dom ...

  5. Linux 网络流量实时监控工具之ntopng详解

    大纲一.前言二.ntopng 简介三.ntopng 功能说明 四.ntopng 安装详解五.ntopng 配置详解 六.ntopng 使用详解注,操作系统 CentOS 5.5 X86_64,软件版本 ...

  6. (转)Linux网络状态工具ss命令使用详解

    Linux网络状态工具ss命令使用详解 原文:http://www.landui.com/help/show-5991.html ss 是 socket statistics 的缩写.顾名思义,ss ...

  7. iOS开发——UI篇OC篇&UICollectionView详解+实例

    UICollectionView详解+实例 实现步骤: 一.新建两个类 1.继承自UIScrollView的子类,比如HMWaterflowView * 瀑布流显示控件,用来显示所有的瀑布流数据 2. ...

  8. 【iOS自定义键盘及键盘切换】详解

    [iOS自定义键盘]详解 实现效果展示: 一.实现的协议方法代码 #import <UIKit/UIKit.h> //创建自定义键盘协议 @protocol XFG_KeyBoardDel ...

  9. Linux 网络编程三(socket代码详解)

    //网络编程客户端 #include <stdio.h> #include <stdlib.h> #include <string.h> #include < ...

随机推荐

  1. 【完全开源】知乎日报UWP版:项目结构说明、关键源代码解释

    目录 说明 项目结构 关键代码 演示视频 说明 上一篇博客将源码放出来了,但是并没有做过多的介绍,所以如果自己硬看可能需要花费很长的时间,尤其这些代码并不是自己写的.项目不算复杂但是也不算简单,这篇文 ...

  2. 在C#代码中应用Log4Net系列教程(附源代码)

    Log4Net应该可以说是DotNet中最流行的开源日志组件了.以前需要苦逼写的日志类,在Log4Net中简单地配置一下就搞定了.没用过Log4Net,真心不知道原来日志组件也可以做得这么灵活,当然这 ...

  3. ABP框架 - 工作单元

    文档目录 本节内容: 简介 在ABP中管理连接和事务 约定的工作单元 UnitOfWork 特性 IUnitOfWorkManager 工作单元详情 禁用工作单元 非事务性工作单元 工作单元方法调用另 ...

  4. linux下select/poll/epoll机制的比较

    select.poll.epoll简介 epoll跟select都能提供多路I/O复用的解决方案.在现在的Linux内核里有都能够支持,其中epoll是Linux所特有,而select则应该是POSI ...

  5. Android测试网络是否连接

    一.布局页面 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns ...

  6. Spring学习记录(十三)---基于xml文件配置AOP

    上一篇讲了用注解配置AOP,现在讲用xml怎么配置AOP 其实逻辑是一样的,只是用xml的方法,要把这种逻辑写出来,告诉spring框架去执行. 例子:这里的例子和上一篇的例子一样.换成xml方式 / ...

  7. 2.Kali安装VMware tools(详细+异常处理)

    dnt@MT:~$ cd /media/cdrom0 进入光驱内 dnt@MT:/media/cdrom0$ ls 查看当前目录下有哪些内容manifest.txt run_upgrader.sh V ...

  8. Android中如何使用命令行查看内嵌数据库SQLite3

    转载博客:http://www.linuxidc.com/Linux/2011-06/37135.htm 在上图中,除了最后一个红色的方框,其它方框都是adb shell下的命令. [1]在Andro ...

  9. 从零开始编写自己的C#框架(22)——添加普通列表页面

    普通列表页面指的是上一章那种有层次感列表以外的正常列表页面,由于上一章已讲解了正常添加页面的相关操作了,所以部分相关的操作本章节就不再罗嗦重复一次了.大家可以试试先用本章内容中的一些简单介绍,自己使用 ...

  10. 使控件具有 Tilt 效果

    步骤1:添加类: /* Copyright (c) 2010 Microsoft Corporation. All rights reserved. Use of this sample source ...