Apple开发_WKWebView

1、简介

  • iOS8之后苹果推荐使用WKWebView替代UIWebView

  • 1.1 主要的特点

    • 更多的支持HTML5的特性;
    • 更快,占用内存可能只有UIWebView的1/3 ~ 1/4;
    • 高达60fps的滚动刷新率和丰富的内置手势;
    • 具有Safari相同的JavaScript引擎;
    • 增加了加载进度属性。
  • 1.2 相关类:

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

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

2、简单使用

  • 2.1 创建与设置

#import<WebKit/WebKit.h>

// 创建网页配置对象
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

// 创建设置对象
WKPreferences *preference = [[WKPreferences alloc] init];
// 最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果
preference.minimumFontSize = 0;
// 设置是否支持javaScript 默认是支持的
preference.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口
preference.javaScriptCanOpenWindowsAutomatically = YES;
// 设置偏好
config.preferences = preference;

// 是使用h5的视频播放器在线播放(YES), 还是使用原生播放器全屏播放(NO)
config.allowsInlineMediaPlayback = YES;
// 设置视频是否需要用户手动播放  设置为NO则会允许自动播放
if (@available(iOS 10.0, *)) {
    config.mediaTypesRequiringUserActionForPlayback = NO;
}
else {
    // 其他版本的设置
}
// 设置是否允许画中画技术 在特定设备上有效
config.allowsPictureInPictureMediaPlayback = YES;
// 设置请求的User-Agent信息中应用程序名称 iOS9后可用
config.applicationNameForUserAgent = @"ChinaDailyForiPad";

// 以下代码适配文本大小
NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
// 用于进行JavaScript注入
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString
                                                 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
                                              forMainFrameOnly:YES];
[config.userContentController addUserScript:wkUScript];

WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CHScreenW, CHScreenH) configuration:config];
// UI代理
webView.UIDelegate = self;
// 导航代理
webView.navigationDelegate = self;
// 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
webView.allowsBackForwardNavigationGestures = YES;

// 创建网页链接
NSURL *url = [NSURL URLWithString:@"https:// www.cnblogs.com/CH520/p/9976053.html"];
// 设置网页请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 加载网页
[webView loadRequest:request];
  • 注意⚠️:iOS9之后默认不支持HTTP协议,别忘了在Info.plist里面添加支持)

  • 2.2 多种加载方法

// 加载本地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对象
  • A WKNavigation object contains information for tracking the loading progress of a webpage.
  • 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.

3、所有相关的类的API

  • 3.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
  • 3.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.3 WKProcessPool内容处理池

    • 这个类没有公开的方法和属性,而且也并不需要配置,可以暂时忽略。
  • 3.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;
    
  • 3.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;
    
  • 3.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;
    
  • 3.7 WKWebsiteDataRecord

    • 同样iOS9.0之后可以使用,website的数据存储记录类型,它只有两个属性:
    // 通常是域名
    @property (nonatomic, readonly, copy) NSString *displayName;
    // 存储的数据类型集
    @property (nonatomic, readonly, copy) NSSet<NSString *> *dataTypes;
    
  • 3.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
  • 3.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
    
  • 3.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;
    
  • 3.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
  • 3.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
    
  • 3.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
    

4、WKWebView与JS实战

  • 初始化的相关内容在这里不再赘述,提几个常常关注的点
  • 4.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;
    		}];
    	}
    }
    
  • 4.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);
    	}
    }
    
  • 4.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.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;
    
    • 以上的方法根据实际需求操作即可。
posted @ 2022-03-24 09:47  CH520  阅读(295)  评论(0编辑  收藏  举报