WKWebView学习笔记

作者: 雨生_ | 来源:发表于2016-05-02 01:05 被阅读36986次

    一、简介

    webView是我们日常开发中不可缺少的一个组件,通常我们都是使用UIWebView来实现的,不过大多数情况下,UIWebView的表现却不尽如人意(最直观的就是内存消耗严重,特别是有视频的时候,有木有!)
    iOS8之后苹果推荐使用WKWebView替代UIWebView,其主要的有点有:

    1. 在性能、稳定性
    2. WKWebView更多的支持HTML5的特性
    3. WKWebView更快,占用内存可能只有UIWebView的1/3 ~ 1/4
    4. WKWebView高达60fps的滚动刷新率和丰富的内置手势
    5. WKWebView具有Safari相同的JavaScript引擎
    6. WKWebView增加了加载进度属性
    7. 将UIWebViewDelegate和UIWebView重构成了14个类与3个协议官方链接

    Classes:

    • WKBackForwardList: 之前访问过的 web 页面的列表,可以通过后退和前进动作来访问到。
    • WKBackForwardListItem: webview 中后退列表里的某一个网页。
    • WKFrameInfo: 包含一个网页的布局信息。
    • WKNavigation: 包含一个网页的加载进度信息。
    • WKNavigationAction: 包含可能让网页导航变化的信息,用于判断是否做出导航变化。
    • WKNavigationResponse: 包含可能让网页导航变化的返回内容信息,用于判断是否做出导航变化。
    • WKPreferences: 概括一个 webview 的偏好设置。
    • WKProcessPool: 表示一个 web 内容加载池。
    • WKUserContentController: 提供使用 JavaScript post 信息和注射 script 的方法。
    • WKScriptMessage: 包含网页发出的信息。
    • WKUserScript: 表示可以被网页接受的用户脚本。
    • WKWebViewConfiguration: 初始化 webview 的设置。
    • WKWindowFeatures: 指定加载新网页时的窗口属性。

    Protocols

    • WKNavigationDelegate: 提供了追踪主窗口网页加载过程和判断主窗口和子窗口是否进行页面加载新页面的相关方法。
    • WKScriptMessageHandler: 提供从网页中收消息的回调方法。
    • WKUIDelegate: 提供用原生控件显示网页的方法回调。

    废话了这么多,用一个刚刚测试过的图来展示下内存优化了

    WKWebView加载视频.png
    UIWebView加载视频.png

    差距了几倍的内存。下面就聊聊WKWebView的使用。

    二、简单使用

    1.首先自然是导入头文件(iOS9之后默认不支持HTTP协议,别忘了在Info.plist里面添加支持)

    #import<WebKit/WebKit.h>
    

    2.初始化


    (1)由于WKWebView的父类是UIView,所以可以用我们最常用的方法来初始化:

    WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.frame];
    

    (2)WKWebView自己也具备一个自己的初始化方法

    - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration*)configuration
    

    这里面WKWebViewConfiguration就是一个上面讲述的重构了类中的一个,负责的内容是:

    A WKWebViewConfiguration object is a collection of properties used to initialize a web view.
    WKWebViewConfiguration 是一个属性的集合 用来初始化web视图。

    这个类包含众多的属性,预知详情请见官方文档,这里介绍几个常用的属性(偏好的设置):

    //初始化一个WKWebViewConfiguration对象
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        //初始化偏好设置属性:preferences
        config.preferences = [WKPreferences new];
        //The minimum font size in points default is 0;
        config.preferences.minimumFontSize = 10;
        //是否支持JavaScript
        config.preferences.javaScriptEnabled = YES;
        //不通过用户交互,是否可以打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:config];
        
        [self.view addSubview:webView];
    

    3.加载网页

    最基础的方法和UIWebView一样

    NSURL *url = [NSURL URLWithString:@"www.jianshu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    

    这里有几个加载的方法:

    //加载本地URL文件
    - (nullable WKNavigation *)loadFileURL:(NSURL *)URL 
                   allowingReadAccessToURL:(NSURL *)readAccessURL
    
    //加载本地HTML字符串
    - (nullable WKNavigation *)loadHTMLString:(NSString *)string
                                      baseURL:(nullable NSURL *)baseURL;
    //加载二进制数据
    - (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL
    

    每个方法都会返回一个WKNavigation对象,官方介绍是

    一个WKNavigation对象包含信息跟踪加载一个网页的进展。
    A WKNavigation object contains information for tracking the loading progress of a webpage.

    导航web视图加载方法返回的对象,也是传递到导航委托方法来唯一地标识一个网页加载从开始到结束。它没有自己的方法或属性。
    A navigation object is returned from the web view load methods and is also passed to the navigation delegate methods to uniquely identify a webpage load from start to finish. It has no method or properties of its own.

    然后我创建了两个WKWebView,加载同样的url,打印的结果是不同的地址:


    这个属性在WKWebView的代理方法里面有用到,我的理解就是用来标记不同的webView的。

    三、所有相关的类的API

    这里的东西比较多,想看一些高级使用的直接跳过看下一节,或者直接下载Demo

    1.WKWebView

    //上文介绍过的偏好配置
    @property (nonatomic, readonly, copy) WKWebViewConfiguration *configuration;
    // 导航代理 
    @property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;
    // 用户交互代理
    @property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;
     
    // 页面前进、后退列表
    @property (nonatomic, readonly, strong) WKBackForwardList *backForwardList;
     
    // 默认构造器
    - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
     
    
    //加载请求API
    - (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
     
    // 加载URL
    - (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);
     
    // 直接加载HTML
    - (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
     
    // 直接加载data
    - (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL NS_AVAILABLE(10_11, 9_0);
     
    // 前进或者后退到某一页面
    - (nullable WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item;
     
    // 页面的标题,支持KVO的
    @property (nullable, nonatomic, readonly, copy) NSString *title;
     
    // 当前请求的URL,支持KVO的
    @property (nullable, nonatomic, readonly, copy) NSURL *URL;
     
    // 标识当前是否正在加载内容中,支持KVO的
    @property (nonatomic, readonly, getter=isLoading) BOOL loading;
     
    // 当前加载的进度,范围为[0, 1]
    @property (nonatomic, readonly) double estimatedProgress;
     
    // 标识页面中的所有资源是否通过安全加密连接来加载,支持KVO的
    @property (nonatomic, readonly) BOOL hasOnlySecureContent;
     
    // 当前导航的证书链,支持KVO
    @property (nonatomic, readonly, copy) NSArray *certificateChain NS_AVAILABLE(10_11, 9_0);
     
    // 是否可以招待goback操作,它是支持KVO的
    @property (nonatomic, readonly) BOOL canGoBack;
     
    // 是否可以执行gofarward操作,支持KVO
    @property (nonatomic, readonly) BOOL canGoForward;
     
    // 返回上一页面,如果不能返回,则什么也不干
    - (nullable WKNavigation *)goBack;
     
    // 进入下一页面,如果不能前进,则什么也不干
    - (nullable WKNavigation *)goForward;
     
    // 重新载入页面
    - (nullable WKNavigation *)reload;
     
    // 重新从原始URL载入
    - (nullable WKNavigation *)reloadFromOrigin;
     
    // 停止加载数据
    - (void)stopLoading;
     
    // 执行JS代码
    - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ __nullable)(__nullable id, NSError * __nullable error))completionHandler;
     
    // 标识是否支持左、右swipe手势是否可以前进、后退
    @property (nonatomic) BOOL allowsBackForwardNavigationGestures;
     
    // 自定义user agent,如果没有则为nil
    @property (nullable, nonatomic, copy) NSString *customUserAgent NS_AVAILABLE(10_11, 9_0);
     
    // 在iOS上默认为NO,标识不允许链接预览
    @property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE(10_11, 9_0);
     
    #if TARGET_OS_IPHONE
    /*! @abstract The scroll view associated with the web view.
     */
    @property (nonatomic, readonly, strong) UIScrollView *scrollView;
    #endif
     
    #if !TARGET_OS_IPHONE
    // 标识是否支持放大手势,默认为NO
    @property (nonatomic) BOOL allowsMagnification;
     
    // 放大因子,默认为1
    @property (nonatomic) CGFloat magnification;
     
    // 根据设置的缩放因子来缩放页面,并居中显示结果在指定的点
    - (void)setMagnification:(CGFloat)magnification centeredAtPoint:(CGPoint)point;
     
    #endif
    

    2. WKPreferences偏好设置

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 设置偏好设置
    config.preferences = [[WKPreferences alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 10;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO,表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    

    3.WKProcessPool内容处理池

    这个类没有公开的方法和属性,而且也并不需要配置,可以暂时忽略。

    4. WKUserContentController内容交互控制器

    我们要通过JS与webview内容交互,就需要到这个类了,它的所有属性及方法说明如下:

    // 只读属性,所有添加的WKUserScript都在这里可以获取到
    @property (nonatomic, readonly, copy) NSArray<WKUserScript *> *userScripts;
     
    // 注入JS
    - (void)addUserScript:(WKUserScript *)userScript;
     
    // 移除所有注入的JS
    - (void)removeAllUserScripts;
     
    // 添加scriptMessageHandler到所有的frames中,则都可以通过
    // window.webkit.messageHandlers.<name>.postMessage(<messageBody>)
    // 发送消息
    // 比如,JS要调用我们原生的方法,就可以通过这种方式了
    - (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
     
    // 根据name移除所注入的scriptMessageHandler
    - (void)removeScriptMessageHandlerForName:(NSString *)name;
    

    5. WKUserScript

    在WKUserContentController中,所有使用到WKUserScript。WKUserContentController是用于与JS交互的类,而所注入的JS是WKUserScript对象。它的所有属性和方法如下:

    // JS源代码
    @property (nonatomic, readonly, copy) NSString *source;
     
    // JS注入时间
    @property (nonatomic, readonly) WKUserScriptInjectionTime injectionTime;
     
    // 只读属性,表示JS是否应该注入到所有的frames中还是只有main frame.
    @property (nonatomic, readonly, getter=isForMainFrameOnly) BOOL forMainFrameOnly;
     
    // 初始化方法,用于创建WKUserScript对象
    // source:JS源代码
    // injectionTime:JS注入的时间
    // forMainFrameOnly:是否只注入main frame
    - (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly;
     
    

    6.WKWebsiteDataStore存储的Web内容

    iOS9.0以后才能使用这个类。是代表webView不同的数据类型,cookies、disk、memory caches、WebSQL、IndexedDB数据库和本地存储。版本适配的化就要放弃了。

    // 默认数据存储
    + (WKWebsiteDataStore *)defaultDataStore;
     
    // 返回非持久化存储,数据不会写入文件系统
    + (WKWebsiteDataStore *)nonPersistentDataStore;
     
    // 只读属性,表示是否是持久化存储
    @property (nonatomic, readonly, getter=isPersistent) BOOL persistent;
     
    // 获取所有web内容的数据存储类型集,比如cookies、disk等
    + (NSSet<NSString *> *)allWebsiteDataTypes;
     
    // 获取某些指定数据存储类型的数据
    - (void)fetchDataRecordsOfTypes:(NSSet<NSString *> *)dataTypes completionHandler:(void (^)(NSArray<WKWebsiteDataRecord *> *))completionHandler;
     
    // 删除某些指定类型的数据
    - (void)removeDataOfTypes:(NSSet<NSString *> *)dataTypes forDataRecords:(NSArray<WKWebsiteDataRecord *> *)dataRecords completionHandler:(void (^)(void))completionHandler;
     
    // 删除某些指定类型的数据且修改日期是指定的日期
    - (void)removeDataOfTypes:(NSSet<NSString *> *)websiteDataTypes modifiedSince:(NSDate *)date completionHandler:(void (^)(void))completionHandler;
     
    

    7. WKWebsiteDataRecord

    同样iOS9.0之后可以使用,website的数据存储记录类型,它只有两个属性:

    // 通常是域名
    @property (nonatomic, readonly, copy) NSString *displayName;
     
    // 存储的数据类型集
    @property (nonatomic, readonly, copy) NSSet<NSString *> *dataTypes;
    

    8. WKNavigationDelegate

    @protocol WKNavigationDelegate <NSObject>
     
    @optional
     
    // 决定导航的动作,通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制,不允许跨域,因此我们要对不能跨域的链接
    // 单独处理。但是,对于Safari是允许跨域的,不用这么处理。
    // 这个是决定是否Request
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
     
    // 决定是否接收响应
    // 这个是决定是否接收response
    // 要获取response,通过WKNavigationResponse对象获取
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
     
    // 当main frame的导航开始请求时,会调用此方法
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
     
    // 当main frame接收到服务重定向时,会回调此方法
    - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
     
    // 当main frame开始加载数据失败时,会回调
    - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
     
    // 当main frame的web内容开始到达时,会回调
    - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
     
    // 当main frame导航完成时,会回调
    - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
     
    // 当main frame最后下载数据失败时,会回调
    - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
     
    // 这与用于授权验证的API,与AFN、UIWebView的授权验证API是一样的
    - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler;
     
    // 当web content处理完成时,会回调
    - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0);
     
    @end
     
    

    9. WKNavigationResponse

    WKNavigationResponse是导航响应类,通过它可以获取相关响应的信息:

    NS_CLASS_AVAILABLE(10_10, 8_0)
    @interface WKNavigationResponse : NSObject
     
    // 是否是main frame
    @property (nonatomic, readonly, getter=isForMainFrame) BOOL forMainFrame;
     
    // 获取响应response
    @property (nonatomic, readonly, copy) NSURLResponse *response;
     
    // 是否显示MIMEType
    @property (nonatomic, readonly) BOOL canShowMIMEType;
     
    @end
    

    10. WKNavigationAction

    WKNavigationAction对象包含关于导航的action的信息,用于make policy decisions。它只有以下几个属性:

    // 正在请求的导航的frame
    @property (nonatomic, readonly, copy) WKFrameInfo *sourceFrame;
    // 目标frame,如果这是新的window,它会是nil
    @property (nullable, nonatomic, readonly, copy) WKFrameInfo *targetFrame; 
    // 导航类型,如下面的小标题WKNavigationType
    @property (nonatomic, readonly) WKNavigationType navigationType;
    // 导航的请求
    @property (nonatomic, readonly, copy) NSURLRequest *request;
    

    11. WKUIDelegate

    @protocol WKUIDelegate <NSObject>
     
    @optional
     
    // 创建新的webview
    // 可以指定配置对象、导航动作对象、window特性
    - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
     
    // webview关闭时回调
    - (void)webViewDidClose:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0);
     
    // 调用JS的alert()方法
    - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
     
    // 调用JS的confirm()方法
    - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
     
    // 调用JS的prompt()方法
    - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
     
    @end
    

    12. WKBackForwardList

    WKBackForwardList表示webview中可以前进或者后退的页面列表。其声明如下:

    NS_CLASS_AVAILABLE(10_10, 8_0)
    @interface WKBackForwardList : NSObject
     
    // 当前正在显示的item(页面)
    @property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *currentItem;
     
    // 后一页,如果没有就是nil
    @property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *backItem;
     
    // 前一页,如果没有就是nil
    @property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *forwardItem;
     
    // 根据下标获取某一个页面的item
    - (nullable WKBackForwardListItem *)itemAtIndex:(NSInteger)index;
     
    // 可以进行goback操作的页面列表
    @property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *backList;
     
    // 可以进行goforward操作的页面列表
    @property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *forwardList;
     
    @end
    

    13. WKBackForwardListItem

    页面导航前进、后退列表项:

    NS_CLASS_AVAILABLE(10_10, 8_0)
    @interface WKBackForwardListItem : NSObject
     
    // 该页面的URL
    @property (readonly, copy) NSURL *URL;
     
    // 该页面的title
    @property (nullable, readonly, copy) NSString *title;
     
    // 初始请求该item的请求的URL
    @property (readonly, copy) NSURL *initialURL;
     
    @end
    

    四WKWebView与JS实战

    初始化的相关内容在这里不再赘述,提几个常常关注的点

    1.添加对WKWebView属性的监听

    这里面处理一下常用的三个:loading、title、estimatedProgress属性,分别用于判断是否正在加载、获取页面标题、当前页面载入进度:

    // 添加KVO监听
        
        [self.webView addObserver:self
                       forKeyPath:@"loading"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
        
        [self.webView addObserver:self
                       forKeyPath:@"title"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
        
        [self.webView addObserver:self
                       forKeyPath:@"estimatedProgress"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
    

    这里不要忘记在界面消失的时候,移除监听

     [_webView removeObserver:self forKeyPath:@"loading" context:nil];//移除kvo
     [_webView removeObserver:self forKeyPath:@"title" context:nil];
     [_webView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
    

    KVO方法:

    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary<NSString *,id> *)change
                           context:(void *)context
    {
        if ([keyPath isEqualToString:@"loading"])
        {
            NSLog(@"loading");
            
        } else if ([keyPath isEqualToString:@"title"])
        {
            self.title = self.webView.title;
        } else if ([keyPath isEqualToString:@"estimatedProgress"])
        {
            NSLog(@"progress: %f", self.webView.estimatedProgress);
            self.progressView.progress = self.webView.estimatedProgress;
        }
        
        // 加载完成
        if (!self.webView.loading)
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.progressView.alpha = 0.0;
            }];
        }
    }
    

    2.配置Js与WebView内容交互

    前面提到了WKUserContentController是用于让Js注入对象的,注入对象后,JS端就可以使用这个方法:

    window.webkit.messageHandlers.<name>.postMessage(<messageBody>) 
    

    用这个方法发送数据给iOS客户端,eg:

    window.webkit.messageHandlers.senderModel.postMessage({body: 'sender message'});
    

    这里面senderModel就是我们要注入的名称,注入之后,就可以在Js端调用了,传数据统一通过body来传递,类型可以随意,但是只支持OC的一些类型(NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull类型。)

    iOS端的部分代码:

    config.userContentController = [[WKUserContentController alloc] init];
     
    // 注入JS对象名称senderModel,当JS通过senderModel来调用时,我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"senderModel"];
    
    #pragma mark - WKScriptMessageHandler
    - (void)userContentController:(WKUserContentController *)userContentController
          didReceiveScriptMessage:(WKScriptMessage *)message {
      if ([message.name isEqualToString:@"senderModel"]) {
        // 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
        //do something
        NSLog(@"%@", message.body);
      }
    }
    

    3. WKUIDelegate代理方法

    与JS的alert、confirm、prompt交互,我们希望用自己的原生界面,而不是JS的,就可以使用这个代理类来实现。

    • alert警告框函数:
    //alert 警告框
    -(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"调用alert提示框" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler();
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        NSLog(@"alert message:%@",message);
    }
    
    • confirm确认框函数:
    //confirm 确认框
    -(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认框" message:@"调用confirm提示框" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(YES);
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(NO);
        }]];
        [self presentViewController:alert animated:YES completion:NULL];
        
        NSLog(@"confirm message:%@", message);
    
    }
    
    • prompt 输入框函数:
    - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入框" message:@"调用输入框" preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.textColor = [UIColor blackColor];
        }];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler([[alert.textFields lastObject] text]);
        }]];
        
        [self presentViewController:alert animated:YES completion:NULL];
    }
    

    4.WKNavigationDelegate

    代理方法在第三节有提到,这里在重复一下吧

    • 用来追踪加载过程的方法:
    //开始加载时调用
    -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
        
    }
    //当内容开始返回时调用
    -(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
        
    }
    //页面加载完成之后调用
    -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
        
    }
    // 页面加载失败时调用
    - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
    {
        
    }
    
    • 页面跳转的代理方法:
    // 接收到服务器跳转请求之后调用
    - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;
    // 在收到响应后,决定是否跳转
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
    // 在发送请求之前,决定是否跳转
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
    

    以上的方法根据实际需求操作即可。

    最后

    Demo地址:WKWebViewDemo
    参考链接:WKWebView的新特性与使用

    相关文章

      网友评论

      • 不辣先生:进度条没看到?代码好像没起作用
      • 懒惰的企鹅:6666666666
      • 林三更:刚好想用WKWebView
        这篇很全,很赞💯
      • Freedom_Coco:楼主,使用wk加载,出现1秒的白屏时间,然后才显示,这个怎么解决呢
      • 洁简:页面加载失败时调用写错了吧
      • 洁简:加载一个错误的地址为何不走didFailProvisionalNavigation
      • b0daca6e9a93:好全,点个赞
      • 空转风:用继承的方式继承了wk,不是在viewController,[self.configuration.userContentController addScriptMessageHandler:self name:@"senderModel"];这个要怎么设置?那个self就爆黄色警告
        空转风:@13678175257_163 谢谢
        aa991dc31a25:(id)self
      • 小八子的开发之路:复制了楼主的代码,被坑了一个小时....网址没有http://,怎么都显示不出来../👋
        赵枫杨:初学,被坑了整整一天了!一直crash,复制了楼主代码马上可以了。感谢
        二月的大胡子:不可否认总结的还行,难免有疏漏。
        ddd686d81b2c:所以说
      • Twenty_:少啦 一句代码 不然会内存泄漏self.webView.configuration.userContentController.removeScriptMessageHandlerForName("senderModel")
      • 371429183029:帅哥 请问一下 我加载的网址的网页 我怎么在OC中抓取网页上面的我想要的信息呢

      本文标题:WKWebView学习笔记

      本文链接:https://www.haomeiwen.com/subject/tuvkrttx.html