当前位置:   article > 正文

IOS混合编程 - UIWebView 与 WKWebView . 基本使用 (一)_didfinishnavigation

didfinishnavigation

UIWebView

UIWebView的基本使用方法 :

就这样就已经整整个baidu的页面展示到app上
下面我们看一下webView的属性与方法

  1. UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  2. self.view = webView;
  3. NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
  4. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  5. [webView loadRequest:request];

UIWebView的层级结构 :


UIWebView的类继承关系

UIWebView的属性 :

  1. // 代理属性 重点需要知道代理方法的使用
  2. @property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;
  3. // 这个是webView内部的scrollView 只读,但是利用这个属性,设置scrollView的代理,就可以控制整个webView的滚动事件
  4. @property(nonatomic, readonly, strong) UIScrollView *scrollView;
  5. // webView的请求,这个属性一般在整个加载完成后才能拿到
  6. @property (nullable, nonatomic, readonly, strong) NSURLRequest *request;
  7. // A Boolean value indicating whether the receiver can move backward. (read-only)
  8. // If YES, able to move backward; otherwise, NO.
  9. // 如果这个属性为YES,才能后退
  10. @property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
  11. // A Boolean value indicating whether the receiver can move forward. (read-only)
  12. // If YES, able to move forward; otherwise, NO.
  13. // 如果这个属性为YES,才能前进
  14. @property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
  15. // A Boolean value indicating whether the receiver is done loading content. (read-only)
  16. // If YES, the receiver is still loading content; otherwise, NO.
  17. // 这个属性很好用,如果为YES证明webView还在加载数据,所有数据加载完毕后,webView就会为No
  18. @property (nonatomic, readonly, getter=isLoading) BOOL loading;
  19. //A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.
  20. //If YES, the webpage is scaled to fit and the user can zoom in and zoom out. If NO, user zooming is disabled. The default value is NO.
  21. // YES代表网页可以缩放,NO代表不可以缩放
  22. @property (nonatomic) BOOL scalesPageToFit;
  23. // 设置某些数据变为链接形式,这个枚举可以设置如电话号,地址,邮箱等转化为链接
  24. @property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);
  25. // iPhone Safari defaults to NO. iPad Safari defaults to YES
  26. // 设置是否使用内联播放器播放视频
  27. @property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0);
  28. // iPhone and iPad Safari both default to YES
  29. // 设置视频是否自动播放
  30. @property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0);
  31. // iPhone and iPad Safari both default to YES
  32. // 设置音频播放是否支持ari play功能
  33. @property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0);
  34. // iPhone and iPad Safari both default to NO
  35. // 设置是否将数据加载入内存后渲染界面
  36. @property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0);
  37. // default is YES
  38. // 设置用户是否能打开keyboard交互
  39. @property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0);
  40. /* IOS7 */ 以后的新特性
  41. // 这个属性用来设置一种模式,当网页的大小超出view时,将网页以翻页的效果展示,枚举如下:
  42. @property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
  43. typedef NS_ENUM(NSInteger, UIWebPaginationMode) {
  44. UIWebPaginationModeUnpaginated, //不使用翻页效果
  45. UIWebPaginationModeLeftToRight, //将网页超出部分分页,从左向右进行翻页
  46. UIWebPaginationModeTopToBottom, //将网页超出部分分页,从上向下进行翻页
  47. UIWebPaginationModeBottomToTop, //将网页超出部分分页,从下向上进行翻页
  48. UIWebPaginationModeRightToLeft //将网页超出部分分页,从右向左进行翻页
  49. };
  50. // This property determines whether certain CSS properties regarding column- and page-breaking are honored or ignored.
  51. // 这个属性决定CSS的属性分页是可用还是忽略。默认是UIWebPaginationBreakingModePage
  52. @property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);
  53. // 设置每一页的长度
  54. @property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);
  55. // 设置每一页的间距
  56. @property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);
  57. // 获取页数
  58. @property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);

还有一些属性请详细翻苹果文档

UIWebView的代理方法 :

UIWebView的代理方法是用的最多的方法,并且一般来说,相对Web页面作处理都在这相应的4个方法中
分别解释一下方法的调用情况

  1. // Sent before a web view begins loading a frame.请求发送前都会调用该方法,返回NO则不处理这个请求
  2. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
  3. // Sent after a web view starts loading a frame. 请求发送之后开始接收响应之前会调用这个方法
  4. - (void)webViewDidStartLoad:(UIWebView *)webView;
  5. // Sent after a web view finishes loading a frame. 请求发送之后,并且服务器已经返回响应之后调用该方法
  6. - (void)webViewDidFinishLoad:(UIWebView *)webView;
  7. // Sent if a web view failed to load a frame. 网页请求失败则会调用该方法
  8. - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;

UIWebView的对象方法

  1. // 加载Data数据创建一个webView
  2. - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL
  3. // 加载本地HTML创建一个webView
  4. - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
  5. // 加载一个请求创建一个webView
  6. - (void)loadRequest:(NSURLRequest *)request
  7. // 刷新网页
  8. - (void)reload;
  9. // 停止网页加载内容
  10. - (void)stopLoading;
  11. // 后退
  12. - (void)goBack;
  13. // 前进
  14. - (void)goForward;
  15. // 执行JS方法
  16. - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script






WKWebView

WKWebView的简介 :

从文档中可以看到,这个是IOS8之后新增的一个类,也是苹果推崇的一个新的类


WKWebView的类层级结构

WKWebView的基本使用方法 :

其实和UIWebView的用法没什么区别
但是WKWebView相对于UIWebView强大了很多,内存的消耗相对少了,所提供的接口也丰富了。
推荐使用
多了一部操作就是需要包含webkit框架
@import webkit

  1. WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  2. self.view = webView;
  3. NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
  4. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  5. [webView loadRequest:request];

WKWebView的属性 :

  1. // UIWebView 中会自动保存Cookie,如果登录了一次下次再次进入的时候,会记住登录状态
  2. // 在WKWebView中,新增一个configuration属性, configuration 让WKWebView知道登录状态,
  3. // configuration 可以通过已有的Cookie进行设置,也可以通过保存上一次的configuration进行设置
  4. // WKWebViewConfiguration类中也有一些相应的属性
  5. @property (nonatomic, readonly, copy) WKWebViewConfiguration *configuration;
  6. // The methods of the WKNavigationDelegate protocol help you track the progress of the web site's main frame navigations and decide load policy for main frame and subframe navigations.
  7. // WKWebView中,加入了网站导航的概念,这个对象决定主框架导航加载方法协议。
  8. @property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;
  9. // The WKUIDelegate class provides methods for presenting native user interface
  10. elements on behalf of a webpage.
  11. // WKWebView中,加入了网站窗口的概念,这个对象决了webView窗口的一些方法协议。
  12. @property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;
  13. A WKBackForwardList object is a list of webpages previously visited in a web view that can be reached by going back or forward.
  14. // WKWebView中,加入了网站列表的概念,这个WEBBackForwardList对象是以前在Web视图访问的网页,可以通过去后退或前进
  15. @property (nonatomic, readonly, strong) WKBackForwardList *backForwardList;

还有很多方法,同样可以查文档看到

WKWebView的代理方法 :

有一些方法和UIWebView是基本一直的,但是因为返回了navigation,所能用到的属性多了很多,另外多了一些方法,将请求与相应的整个过程

  1. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
  2. NSLog(@"webViewWebContentProcessDidTerminate: 当Web视图的网页内容被终止时调用。");
  3. }
  4. - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
  5. {
  6. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  7. NSLog(@"webView:didFinishNavigation: 响应渲染完成后调用该方法 webView : %@ -- navigation : %@ \n\n",webView,navigation);
  8. }
  9. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
  10. {
  11. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  12. NSLog(@"webView:didStartProvisionalNavigation: 开始请求 \n\n");
  13. }
  14. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
  15. NSLog(@"webView:didCommitNavigation: 响应的内容到达主页面的时候响应,刚准备开始渲染页面应用 \n\n");
  16. }
  17. // error
  18. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  19. // 类似 UIWebView 的- webView:didFailLoadWithError:
  20. NSLog(@"webView:didFailProvisionalNavigation:withError: 启动时加载数据发生错误就会调用这个方法。 \n\n");
  21. }
  22. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
  23. NSLog(@"webView:didFailNavigation: 当一个正在提交的页面在跳转过程中出现错误时调用这个方法。 \n\n");
  24. }
  25. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
  26. NSLog(@"请求前会先进入这个方法 webView:decidePolicyForNavigationActiondecisionHandler: %@ \n\n ",navigationAction.request);
  27. decisionHandler(WKNavigationActionPolicyAllow);
  28. }
  29. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
  30. NSLog(@"返回响应前先会调用这个方法 并且已经能接收到响应webView:decidePolicyForNavigationResponse:decisionHandler: Response?%@ \n\n",navigationResponse.response);
  31. decisionHandler(WKNavigationResponsePolicyAllow);
  32. }
  33. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
  34. NSLog(@"webView:didReceiveServerRedirectForProvisionalNavigation: 重定向的时候就会调用 \n\n");
  35. }

WKWebView的对象方法 :

这些方法,基本上和UIWebView中的使用用法是一致的,所以

  1. // 这是加载网页最常用的一种方式,通过一个网页URL来加载一个WKWebView,这个URL可以是远程的也可以是本地的,例如我加载百度的主页
  2. - (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
  3. // 根据一个文件,加载一个WKWebView
  4. - (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);
  5. // 这个方法需要将html文件读取为字符串从而加载为WKWebView,其中baseURL是我们自己设置的一个路径,用于寻找html文件中引用的图片等素材。
  6. - (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
  7. // 这个方式使用的比较少,但也更加自由,其中data是文件数据,MIMEType是文件类型,characterEncodingName是编码类型,baseURL是素材资源路径
  8. - (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL NS_AVAILABLE(10_11, 9_0);

基本使用

下面会总结一些我在开发过程中遇到的坑,和解决问题的一些思路,不过在此之前我发现,如果要webView玩得好,有以下几点的只是也需要掌握好,因为我认为在H5崛起的今天,源生App和H5的交互之间会产生比较大改变,而且源生与H5之间的混编,越来越被重视.所以 :

  1. 源生技术,特别是有关于webView这一块的API要非常熟练,
  2. js语法, js的语法需要熟练,特别是操作document的几个常用js,标签需要用得滚瓜烂熟.
  3. 要非常了解网络请求 - 响应的机制,理解请求头,响应头,等等.HTTP的整套协议

需求一 : 展示一个网页,但是需要隐藏一部分页面

首先看看百度的页面,这是用Chrome浏览器打开的开发者模式
基本界面组成如下,基本使用用法请详情百度,这里不作介绍


假设现在想将这个Logo由网页开始加载就去掉


百度的logo就是一个div套着一个image标签


  1. - (void)webViewDidFinishLoad:(UIWebView *)webView
  2. {
  3. // 在HTML标签都加载完成后,开始处理HTML标签,调用JS,操作document
  4. [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('plus-card').remove();"];
  5. }

就这样, logo标签就被去掉了,思路就是等HTML加载完成后,操作JS从而操作document标签从而改变整个html页面的应用,下图是去掉整个Body主题内容后的结果


另外还可以将一段函数封装到里面,执行函数,原理是通过stringByEvaluatingJavaScriptFromString将JS函数写进head标签中,然后再调用该函数

  1. // 自定义editMyLogo函数
  2. [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
  3. "script.type = 'text/javascript';"
  4. "script.text = \"function editMyLogo() { "
  5. "var logo = document.getElementById('logo');"
  6. "logo.innerHTML= logo.innerHTML + '这是我自己定义的名字';"
  7. "var imglist = logo.getElementsByTagName('IMG');"
  8. "for (i=0 ; i < imglist.length ; i++ ){"
  9. "imglist[i].src = 'http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png';"
  10. "}"
  11. "}\";"
  12. "document.getElementsByTagName('head')[0].appendChild(script);"];
  13. // 执行editMyLogo函数
  14. [webView stringByEvaluatingJavaScriptFromString:@"editMyLogo();"];

效果如下 :


有几点问题,这种操作是在webViewDidFinishLoad方法下进行的,webViewDidFinishLoad方法是webView的document已经渲染好后,再去处理这个这个页面.

  1. 你会发现有时候会出现一些闪屏现象,原因是渲染过后,内部处理JS代码后,页面会再渲染一次
  2. 资源浪费,假设这边的需求只需要显示10%的内容,却要加载100%的内容,不过这一方面还需要网页端作出很好的适配
  3. 某些时候,JS会失效,不知道什么原因,有些时候自定义加载的JS的方法并没有执行到.等于内容并没有屏蔽
  4. 等等..

需求二 : 怎样处理403,404的情况 ?


  1. @property (nonatomic, assign) BOOL isPost; // 定义一个变量
  2. // 每一个请求开始发送前都会调用这个方法
  3. // 1, 定义一个全局变量currentRequest,用作保存当前的请求
  4. // 2, 将请求转换成data,然后处理data再将data作为请求数据再次请求
  5. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
  6. if (_isPost) {
  7. NSHTTPURLResponse *response = nil;
  8. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
  9. if (response.statusCode == 404) {
  10. // 这里处理 404 代码
  11. } else if (response.statusCode == 403) {
  12. // 这里处理 403 代码
  13. } else {
  14. _isPost = true;
  15. [webView loadData:data MIMEType:@"text/html" textEncodingName:@"NSUTF8StringEncoding" baseURL:[request URL]];
  16. }
  17. return NO;
  18. }else{
  19. NSLog(@"\n\n shouldStartLoadWithRequest请求准备 -- %@ \n\n ",request);
  20. _isPost = NO;
  21. return YES;
  22. }
  23. }

需求一 : 进一步改进


在处理HTML这里,将你想隐藏的页面,加上 display:none 属性,
或者,将整段HTML标签去掉.



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

闽ICP备14008679号