iOS (一) - UIWebView 与 WKWebView . 基本使用

随说 : 最近有个需求,是将公司的一个内网的页面嵌套在app中作为一个模块.这不是很简单的webView请求一下就行了么?其实内里大有乾坤.自己也将思路整理一遍

UIWebView

UIWebView的基本使用方法 :

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

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

UIWebView的层级结构 :


UIWebView的类继承关系

UIWebView的属性 :

// 代理属性 重点需要知道代理方法的使用
@property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;

// 这个是webView内部的scrollView 只读,但是利用这个属性,设置scrollView的代理,就可以控制整个webView的滚动事件
@property(nonatomic, readonly, strong) UIScrollView *scrollView;

// webView的请求,这个属性一般在整个加载完成后才能拿到
@property (nullable, nonatomic, readonly, strong) NSURLRequest *request;

// A Boolean value indicating whether the receiver can move backward. (read-only)
// If YES, able to move backward; otherwise, NO.
// 如果这个属性为YES,才能后退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;

// A Boolean value indicating whether the receiver can move forward. (read-only)
// If YES, able to move forward; otherwise, NO.
// 如果这个属性为YES,才能前进
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;

// A Boolean value indicating whether the receiver is done loading content. (read-only)
// If YES, the receiver is still loading content; otherwise, NO.
// 这个属性很好用,如果为YES证明webView还在加载数据,所有数据加载完毕后,webView就会为No
@property (nonatomic, readonly, getter=isLoading) BOOL loading;

//A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.
//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.
// YES代表网页可以缩放,NO代表不可以缩放
@property (nonatomic) BOOL scalesPageToFit;

// 设置某些数据变为链接形式,这个枚举可以设置如电话号,地址,邮箱等转化为链接
@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);

// iPhone Safari defaults to NO. iPad Safari defaults to YES
// 设置是否使用内联播放器播放视频
@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0); 

// iPhone and iPad Safari both default to YES
// 设置视频是否自动播放
@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0); 

// iPhone and iPad Safari both default to YES
// 设置音频播放是否支持ari play功能
@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0); 

// iPhone and iPad Safari both default to NO
// 设置是否将数据加载入内存后渲染界面
@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0); 

// default is YES
// 设置用户是否能打开keyboard交互
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0); 

/* IOS7 */ 以后的新特性
// 这个属性用来设置一种模式,当网页的大小超出view时,将网页以翻页的效果展示,枚举如下:
@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSInteger, UIWebPaginationMode) { 
UIWebPaginationModeUnpaginated, //不使用翻页效果 
UIWebPaginationModeLeftToRight, //将网页超出部分分页,从左向右进行翻页 
UIWebPaginationModeTopToBottom, //将网页超出部分分页,从上向下进行翻页 
UIWebPaginationModeBottomToTop, //将网页超出部分分页,从下向上进行翻页 
UIWebPaginationModeRightToLeft //将网页超出部分分页,从右向左进行翻页 
};

// This property determines whether certain CSS properties regarding column- and page-breaking are honored or ignored. 
// 这个属性决定CSS的属性分页是可用还是忽略。默认是UIWebPaginationBreakingModePage 
@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);

// 设置每一页的长度
@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);

// 设置每一页的间距
@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);

// 获取页数
@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);

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

UIWebView的代理方法 :

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

    // Sent before a web view begins loading a frame.请求发送前都会调用该方法,返回NO则不处理这个请求
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

    // Sent after a web view starts loading a frame. 请求发送之后开始接收响应之前会调用这个方法
    - (void)webViewDidStartLoad:(UIWebView *)webView;

    // Sent after a web view finishes loading a frame. 请求发送之后,并且服务器已经返回响应之后调用该方法
    - (void)webViewDidFinishLoad:(UIWebView *)webView;

    // Sent if a web view failed to load a frame. 网页请求失败则会调用该方法
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;

UIWebView的对象方法

// 加载Data数据创建一个webView
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

// 加载本地HTML创建一个webView
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

// 加载一个请求创建一个webView
- (void)loadRequest:(NSURLRequest *)request

// 刷新网页
- (void)reload;

// 停止网页加载内容
- (void)stopLoading;

// 后退
- (void)goBack;

// 前进
- (void)goForward;

// 执行JS方法
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script






WKWebView

WKWebView的简介 :

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


WKWebView的类层级结构

WKWebView的基本使用方法 :

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

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

WKWebView的属性 :

// UIWebView 中会自动保存Cookie,如果登录了一次下次再次进入的时候,会记住登录状态
// 在WKWebView中,新增一个configuration属性,  configuration 让WKWebView知道登录状态,
// configuration 可以通过已有的Cookie进行设置,也可以通过保存上一次的configuration进行设置
// WKWebViewConfiguration类中也有一些相应的属性
@property (nonatomic, readonly, copy) WKWebViewConfiguration *configuration;

// 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.
// WKWebView中,加入了网站导航的概念,这个对象决定主框架导航加载方法协议。
@property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;

// The WKUIDelegate class provides methods for presenting native user interface 
elements on behalf of a webpage.
// WKWebView中,加入了网站窗口的概念,这个对象决了webView窗口的一些方法协议。
@property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;

A WKBackForwardList object is a list of webpages previously visited in a web view that can be reached by going back or forward.
// WKWebView中,加入了网站列表的概念,这个WEBBackForwardList对象是以前在Web视图访问的网页,可以通过去后退或前进
@property (nonatomic, readonly, strong) WKBackForwardList *backForwardList;

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

WKWebView的代理方法 :

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

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    NSLog(@"webViewWebContentProcessDidTerminate:  当Web视图的网页内容被终止时调用。");
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"webView:didFinishNavigation:  响应渲染完成后调用该方法   webView : %@  -- navigation : %@  \n\n",webView,navigation);
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSLog(@"webView:didStartProvisionalNavigation:  开始请求  \n\n");
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"webView:didCommitNavigation:   响应的内容到达主页面的时候响应,刚准备开始渲染页面应用 \n\n");
}


// error
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    // 类似 UIWebView 的- webView:didFailLoadWithError:

    NSLog(@"webView:didFailProvisionalNavigation:withError: 启动时加载数据发生错误就会调用这个方法。  \n\n");
}



- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"webView:didFailNavigation: 当一个正在提交的页面在跳转过程中出现错误时调用这个方法。  \n\n");
}



- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

    NSLog(@"请求前会先进入这个方法  webView:decidePolicyForNavigationActiondecisionHandler: %@   \n\n  ",navigationAction.request);

    decisionHandler(WKNavigationActionPolicyAllow);

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

    NSLog(@"返回响应前先会调用这个方法  并且已经能接收到响应webView:decidePolicyForNavigationResponse:decisionHandler: Response?%@  \n\n",navigationResponse.response);

    decisionHandler(WKNavigationResponsePolicyAllow);
}



- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

    NSLog(@"webView:didReceiveServerRedirectForProvisionalNavigation: 重定向的时候就会调用  \n\n");
}

WKWebView的对象方法 :

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

// 这是加载网页最常用的一种方式,通过一个网页URL来加载一个WKWebView,这个URL可以是远程的也可以是本地的,例如我加载百度的主页
- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;

// 根据一个文件,加载一个WKWebView
- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);

// 这个方法需要将html文件读取为字符串从而加载为WKWebView,其中baseURL是我们自己设置的一个路径,用于寻找html文件中引用的图片等素材。
- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;

// 这个方式使用的比较少,但也更加自由,其中data是文件数据,MIMEType是文件类型,characterEncodingName是编码类型,baseURL是素材资源路径
- (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浏览器打开的开发者模式
基本界面组成如下,基本使用用法请详情百度,这里不作介绍

扫描二维码关注公众号,回复: 4762201 查看本文章

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


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


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

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


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

// 自定义editMyLogo函数
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function editMyLogo() { "
     "var logo = document.getElementById('logo');"
     "logo.innerHTML= logo.innerHTML + '这是我自己定义的名字';"
     "var imglist = logo.getElementsByTagName('IMG');"
     "for (i=0 ; i < imglist.length ; i++ ){"
     "imglist[i].src = 'http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png';"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];

    // 执行editMyLogo函数
    [webView stringByEvaluatingJavaScriptFromString:@"editMyLogo();"];

效果如下 :


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

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

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


@property (nonatomic, assign) BOOL isPost; // 定义一个变量

// 每一个请求开始发送前都会调用这个方法
// 1, 定义一个全局变量currentRequest,用作保存当前的请求
// 2, 将请求转换成data,然后处理data再将data作为请求数据再次请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    if (!_isPost) {
        NSHTTPURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        if (response.statusCode == 404) {
            // 这里处理 404 代码
        } else if (response.statusCode == 403) {
            // 这里处理 403 代码
        } else {

            _isPost = true;
            [webView loadData:data MIMEType:@"text/html" textEncodingName:@"NSUTF8StringEncoding" baseURL:[request URL]];

        }
        return NO;
    }else{
        NSLog(@"\n\n shouldStartLoadWithRequest请求准备 --  %@ \n\n ",request);
        _isPost = NO;
        return YES;
    }
}

需求一 : 进一步改进


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




文/travin(简书作者)
原文链接:http://www.jianshu.com/p/b3e7fa514ab7
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

猜你喜欢

转载自blog.csdn.net/wssxy/article/details/54619023