当前位置:   article > 正文

iOS_UIWebView、WKWebView使用详解_ios oc decidepolicyfornavigationaction 设置header

ios oc decidepolicyfornavigationaction 设置header


转自:http://www.jianshu.com/p/556c988e2707

github代码下载

UIWebView下载

WKWebView下载


一、整体介绍

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

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

二、UIWebView使用说明

1 举例:简单的使用

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

  1. - (void)simpleExampleTest {
  2. // 1.创建webview,并设置大小,"20"为状态栏高度
  3. UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
  4. // 2.创建请求
  5. NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
  6. // 3.加载网页
  7. [webView loadRequest:request];
  8. // 最后将webView添加到界面
  9. [self.view addSubview:webView];
  10. }
2 一些实用函数
  • 加载函数。
  1. - (void)loadRequest:(NSURLRequest *)request;
  2. - (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
  3. - (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. // 1.获取url
  2. NSURL *url = [NSURL fileURLWithPath:@"/Users/coohua/Desktop/bigIcon.png"];
  3. // 2.创建请求
  4. NSURLRequest *request=[NSURLRequest requestWithURL:url];
  5. // 3.加载请求
  6. [self.webView loadRequest:request];
  • 网页导航刷新有关函数
  1. // 刷新
  2. - (void)reload;
  3. // 停止加载
  4. - (void)stopLoading;
  5. // 后退函数
  6. - (void)goBack;
  7. // 前进函数
  8. - (void)goForward;
  9. // 是否可以后退
  10. @property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
  11. // 是否可以向前
  12. @property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
  13. // 是否正在加载
  14. @property (nonatomic, readonly, getter=isLoading) BOOL loading;
3 代理协议使用:UIWebViewDelegate

一共有四个方法

  1. /// 是否允许加载网页,也可获取js要打开的url,通过截取此url可与js交互
  2. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  3. NSString *urlString = [[request URL] absoluteString];
  4. urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  5. NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
  6. NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);
  7. return YES;
  8. }
  9. /// 开始加载网页
  10. - (void)webViewDidStartLoad:(UIWebView *)webView {
  11. NSURLRequest *request = webView.request;
  12. NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]);
  13. }
  14. /// 网页加载完成
  15. - (void)webViewDidFinishLoad:(UIWebView *)webView {
  16. NSURLRequest *request = webView.request;
  17. NSURL *url = [request URL];
  18. if ([url.path isEqualToString:@"/normal.html"]) {
  19. NSLog(@"isEqualToString");
  20. }
  21. NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);
  22. NSLog(@"%@",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
  23. }
  24. /// 网页加载错误
  25. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  26. NSURLRequest *request = webView.request;
  27. NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);
  28. }
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:
  1. // 实现自动定位js代码, htmlLocationID为定位的位置(由js开发人员给出),实现自动定位代码,应该在网页加载完成之后再调用
  2. NSString *javascriptStr = [NSString stringWithFormat:@"window.location.href = '#%@'",htmlLocationID];
  3. // webview执行代码
  4. [self.webView stringByEvaluatingJavaScriptFromString:javascriptStr];
  5. // 获取网页的title
  6. NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]
  • 与js交互的实例

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


火狐浏览器中查看

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

  1. - (void)deleteNewsSource {
  2. // 1.去掉页面标题
  3. NSMutableString *str = [NSMutableString string];
  4. // 去掉导航页,如果想把“腾讯新闻”导航栏一并去掉,就打开注释
  5. // [str appendString:@"document.getElementsByClassName('g-header')[0].style.display = 'none';"];
  6. // 来源
  7. [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];}"];
  8. // 执行js代码
  9. [_webView stringByEvaluatingJavaScriptFromString:str];
  10. }

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

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

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

三、WKWebView使用说明

1 简单使用

与UIWebview一样,仅需三步:

  1. - (void)simpleExampleTest {
  2. // 1.创建webview,并设置大小,"20"为状态栏高度
  3. WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
  4. // 2.创建请求
  5. NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
  6. // 3.加载网页
  7. [webView loadRequest:request];
  8. // 最后将webView添加到界面
  9. [self.view addSubview:webView];
  10. }
2 一些实用函数
  • 加载网页函数
    相比UIWebview,WKWebView也支持各种文件格式,并新增了loadFileURL函数,顾名思义加载本地文件。
  1. /// 模拟器调试加载mac本地文件
  2. - (void)loadLocalFile {
  3. // 1.创建webview,并设置大小,"20"为状态栏高度
  4. WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
  5. // 2.创建url userName:电脑用户名
  6. NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
  7. // 3.加载文件
  8. [webView loadFileURL:url allowingReadAccessToURL:url];
  9. // 最后将webView添加到界面
  10. [self.view addSubview:webView];
  11. }
  12. /// 其它三个加载函数
  13. - (WKNavigation *)loadRequest:(NSURLRequest *)request;
  14. - (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
  15. - (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL;
  • 网页导航刷新相关函数
    和UIWebview几乎一样,不同的是有返回值,WKNavigation(已更新),另外增加了函数reloadFromOrigingoToBackForwardListItem
    • reloadFromOrigin会比较网络数据是否有变化,没有变化则使用缓存,否则从新请求。
    • goToBackForwardListItem:比向前向后更强大,可以跳转到某个指定历史页面
  1. @property (nonatomic, readonly) BOOL canGoBack;
  2. @property (nonatomic, readonly) BOOL canGoForward;
  3. - (WKNavigation *)goBack;
  4. - (WKNavigation *)goForward;
  5. - (WKNavigation *)reload;
  6. - (WKNavigation *)reloadFromOrigin; // 增加的函数
  7. - (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item; // 增加的函数
  8. - (void)stopLoading;
  • 一些常用属性
    • allowsBackForwardNavigationGestures:BOOL类型,是否允许左右划手势导航,默认不允许
    • estimatedProgress:加载进度,取值范围0~1
    • title:页面title
    • .scrollView.scrollEnabled:是否允许上下滚动,默认允许
    • backForwardList:WKBackForwardList类型,访问历史列表,可以通过前进后退按钮访问,或者通过goToBackForwardListItem函数跳到指定页面
3 代理协议使用

一共有三个代理协议:

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

三个是否允许加载函数:

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

追踪加载过程函数:

  1. /// 2 页面开始加载
  2. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
  3. /// 4 开始获取到网页内容时返回
  4. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
  5. /// 5 页面加载完成之后调用
  6. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
  7. /// 页面加载失败时调用
  8. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
  • WKScriptMessageHandler:必须实现的函数,是APP与js交互,提供从网页中收消息的回调方法
  1. /// message: 收到的脚本信息.
  2. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
  • WKUIDelegate:UI界面相关,原生控件支持,三种提示框:输入、确认、警告。首先将web提示框拦截然后再做处理。
  1. /// 创建一个新的WebView
  2. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
  3. /// 输入框
  4. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
  5. /// 确认框
  6. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
  7. /// 警告框
  8. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;

四、示例代码

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

  1. /// 控件高度
  2. #define kSearchBarH 44
  3. #define kBottomViewH 44
  4. /// 屏幕大小尺寸
  5. #define kScreenWidth [UIScreen mainScreen].bounds.size.width
  6. #define kScreenHeight [UIScreen mainScreen].bounds.size.height
  7. #import "ViewController.h"
  8. #import <WebKit/WebKit.h>
  9. @interface ViewController () <UISearchBarDelegate, WKNavigationDelegate>
  10. @property (nonatomic, strong) UISearchBar *searchBar;
  11. /// 网页控制导航栏
  12. @property (weak, nonatomic) UIView *bottomView;
  13. @property (nonatomic, strong) WKWebView *wkWebView;
  14. @property (weak, nonatomic) UIButton *backBtn;
  15. @property (weak, nonatomic) UIButton *forwardBtn;
  16. @property (weak, nonatomic) UIButton *reloadBtn;
  17. @property (weak, nonatomic) UIButton *browserBtn;
  18. @property (weak, nonatomic) NSString *baseURLString;
  19. @end
  20. @implementation ViewController
  21. - (void)viewDidLoad {
  22. [super viewDidLoad];
  23. // [self simpleExampleTest];
  24. [self addSubViews];
  25. [self refreshBottomButtonState];
  26. [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]];
  27. }
  28. - (void)simpleExampleTest {
  29. // 1.创建webview,并设置大小,"20"为状态栏高度
  30. WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
  31. // 2.创建请求
  32. NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
  33. // // 3.加载网页
  34. [webView loadRequest:request];
  35. // [webView loadFileURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"] allowingReadAccessToURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]];
  36. // 最后将webView添加到界面
  37. [self.view addSubview:webView];
  38. }
  39. /// 模拟器加载mac本地文件
  40. - (void)loadLocalFile {
  41. // 1.创建webview,并设置大小,"20"为状态栏高度
  42. WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
  43. // 2.创建url userName:电脑用户名
  44. NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
  45. // 3.加载文件
  46. [webView loadFileURL:url allowingReadAccessToURL:url];
  47. // 最后将webView添加到界面
  48. [self.view addSubview:webView];
  49. }
  50. - (void)addSubViews {
  51. [self addBottomViewButtons];
  52. [self.view addSubview:self.searchBar];
  53. [self.view addSubview:self.wkWebView];
  54. }
  55. - (void)addBottomViewButtons {
  56. // 记录按钮个数
  57. int count = 0;
  58. // 添加按钮
  59. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  60. [button setTitle:@"后退" forState:UIControlStateNormal];
  61. [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
  62. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
  63. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  64. [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
  65. button.tag = ++count; // 标记按钮
  66. [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
  67. [self.bottomView addSubview:button];
  68. self.backBtn = button;
  69. button = [UIButton buttonWithType:UIButtonTypeCustom];
  70. [button setTitle:@"前进" forState:UIControlStateNormal];
  71. [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
  72. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
  73. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  74. [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
  75. button.tag = ++count;
  76. [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
  77. [self.bottomView addSubview:button];
  78. self.forwardBtn = button;
  79. button = [UIButton buttonWithType:UIButtonTypeCustom];
  80. [button setTitle:@"重新加载" forState:UIControlStateNormal];
  81. [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
  82. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
  83. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  84. [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
  85. button.tag = ++count;
  86. [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
  87. [self.bottomView addSubview:button];
  88. self.reloadBtn = button;
  89. button = [UIButton buttonWithType:UIButtonTypeCustom];
  90. [button setTitle:@"Safari" forState:UIControlStateNormal];
  91. [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
  92. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
  93. [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
  94. [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
  95. button.tag = ++count;
  96. [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
  97. [self.bottomView addSubview:button];
  98. self.browserBtn = button;
  99. // 统一设置frame
  100. [self setupBottomViewLayout];
  101. }
  102. - (void)setupBottomViewLayout
  103. {
  104. int count = 4;
  105. CGFloat btnW = 80;
  106. CGFloat btnH = 30;
  107. CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2;
  108. // 按钮间间隙
  109. CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count;
  110. CGFloat btnX = margin * 0.5;
  111. self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
  112. btnX = self.backBtn.frame.origin.x + btnW + margin;
  113. self.forwardBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
  114. btnX = self.forwardBtn.frame.origin.x + btnW + margin;
  115. self.reloadBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
  116. btnX = self.reloadBtn.frame.origin.x + btnW + margin;
  117. self.browserBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
  118. }
  119. /// 刷新按钮是否允许点击
  120. - (void)refreshBottomButtonState {
  121. if ([self.wkWebView canGoBack]) {
  122. self.backBtn.enabled = YES;
  123. } else {
  124. self.backBtn.enabled = NO;
  125. }
  126. if ([self.wkWebView canGoForward]) {
  127. self.forwardBtn.enabled = YES;
  128. } else {
  129. self.forwardBtn.enabled = NO;
  130. }
  131. }
  132. /// 按钮点击事件
  133. - (void)onBottomButtonsClicled:(UIButton *)sender {
  134. switch (sender.tag) {
  135. case 1:
  136. {
  137. [self.wkWebView goBack];
  138. [self refreshBottomButtonState];
  139. }
  140. break;
  141. case 2:
  142. {
  143. [self.wkWebView goForward];
  144. [self refreshBottomButtonState];
  145. }
  146. break;
  147. case 3:
  148. [self.wkWebView reload];
  149. break;
  150. case 4:
  151. [[UIApplication sharedApplication] openURL:self.wkWebView.URL];
  152. break;
  153. default:
  154. break;
  155. }
  156. }
  157. #pragma mark - WKWebView WKNavigationDelegate 相关
  158. /// 是否允许加载网页 在发送请求之前,决定是否跳转
  159. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  160. NSString *urlString = [[navigationAction.request URL] absoluteString];
  161. urlString = [urlString stringByRemovingPercentEncoding];
  162. // NSLog(@"urlString=%@",urlString);
  163. // 用://截取字符串
  164. NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
  165. if ([urlComps count]) {
  166. // 获取协议头
  167. NSString *protocolHead = [urlComps objectAtIndex:0];
  168. NSLog(@"protocolHead=%@",protocolHead);
  169. }
  170. decisionHandler(WKNavigationActionPolicyAllow);
  171. }
  172. #pragma mark - searchBar代理方法
  173. /// 点击搜索按钮
  174. - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  175. // 创建url
  176. NSURL *url = nil;
  177. NSString *urlStr = searchBar.text;
  178. // 如果file://则为打开bundle本地文件,http则为网站,否则只是一般搜索关键字
  179. if([urlStr hasPrefix:@"file://"]){
  180. NSRange range = [urlStr rangeOfString:@"file://"];
  181. NSString *fileName = [urlStr substringFromIndex:range.length];
  182. url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
  183. // 如果是模拟器加载电脑上的文件,则用下面的代码
  184. // url = [NSURL fileURLWithPath:fileName];
  185. }else if(urlStr.length>0){
  186. if ([urlStr hasPrefix:@"http://"]) {
  187. url=[NSURL URLWithString:urlStr];
  188. } else {
  189. urlStr=[NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@",urlStr];
  190. }
  191. urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  192. url=[NSURL URLWithString:urlStr];
  193. }
  194. NSURLRequest *request=[NSURLRequest requestWithURL:url];
  195. // 加载请求页面
  196. [self.wkWebView loadRequest:request];
  197. }
  198. #pragma mark - 懒加载
  199. - (UIView *)bottomView {
  200. if (_bottomView == nil) {
  201. UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];
  202. view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
  203. [self.view addSubview:view];
  204. _bottomView = view;
  205. }
  206. return _bottomView;
  207. }
  208. - (UISearchBar *)searchBar {
  209. if (_searchBar == nil) {
  210. UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kSearchBarH)];
  211. searchBar.delegate = self;
  212. searchBar.text = @"http://www.cnblogs.com/mddblog/";
  213. _searchBar = searchBar;
  214. }
  215. return _searchBar;
  216. }
  217. - (WKWebView *)wkWebView {
  218. if (_wkWebView == nil) {
  219. WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20 + kSearchBarH, kScreenWidth, kScreenHeight - 20 - kSearchBarH - kBottomViewH)];
  220. webView.navigationDelegate = self;
  221. // webView.scrollView.scrollEnabled = NO;
  222. // webView.backgroundColor = [UIColor colorWithPatternImage:self.image];
  223. // 允许左右划手势导航,默认允许
  224. webView.allowsBackForwardNavigationGestures = YES;
  225. _wkWebView = webView;
  226. }
  227. return _wkWebView;
  228. }
  229. @end



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/109500
推荐阅读
相关标签
  

闽ICP备14008679号