http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 5393|回复: 5

[基础] WKWebView详解

[复制链接]
发表于 2018-12-29 15:41:58 | 显示全部楼层 |阅读模式

WKWebView是iOS8.0苹果推出的新框架
Wekkit中的核心控件,它的出现就是为了解决UIWebView的各种问题,在实际运用中也明显感受到了它的优势.


WKWebView基本和UIWebView差不多,我们可以用来加载HTML,TXT,PDF,doc等文件,当然更常用的还是加载web页面.


WKWebView给出的加载方式有四种,例:


[Objective-C] 纯文本查看 复制代码
//将文件转为data的方式进行加载,使用时需要注意不同格式的mimeType要对应,而且是iOS9后才有的
[web loadData:data MIMEType:mimeType characterEncodingName:@"UTF-8" baseURL:url];
//最常用的方式
[web loadRequest:request];
//用来加载HTML语言
[web loadHTMLString:htmlString baseURL:nil];
//以URL的方式加载注意iOS9后的
[web loadFileURL:url allowingReadAccessToURL:url];


加载不同文件格式要使用不同的方法,不然会出现加载失败或者乱码的问题.


加载网页:初始化我们往往会用到


[Objective-C] 纯文本查看 复制代码
//初始化
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration


利用WKWebViewConfiguration我们可以进行设置,其中配置属性主要有


[Objective-C] 纯文本查看 复制代码
//内容加载池,可以在多个webview上设置同一个WKProcessPool来共享cookie等
@property (nonatomic, strong) WKProcessPool *processPool;
//可以配置javaScript一些属性,如minimumFontSize设置最小字体
@property (nonatomic, strong) WKPreferences *preferences;
//主要用来与原生交互的
@property (nonatomic, strong) WKUserContentController *userContentController;
//存储数据iOS9以后
@property (nonatomic, strong) WKWebsiteDataStore *websiteDataStore;
//设置是否使用内联播放器播放视频
@property (nonatomic) BOOL allowsInlineMediaPlayback;
//iOS10后 是否允许自动播放
@property (nonatomic) WKAudiovisualMediaTypes mediaTypesRequiringUserActionForPlayback;
//是否允许web页面的缩放
@property (nonatomic) BOOL ignoresViewportScaleLimits;


另外WKWebView本身也可以设置或读取一些属性


[Objective-C] 纯文本查看 复制代码
//导航代理,加载成功,失败允许跳转等
@property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;
//主要负责一些弹出框是否弹出
@property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;
//当前页面标题
@property (nullable, nonatomic, readonly, copy) NSString *title;
//当前页面的URL
@property (nullable, nonatomic, readonly, copy) NSURL *URL;
//是否正在加载
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
//加载进度
@property (nonatomic, readonly) double estimatedProgress;
//是否通过安全加密链接加载
@property (nonatomic, readonly) BOOL hasOnlySecureContent;
//是否可以返回
@property (nonatomic, readonly) BOOL canGoBack;
//是否可以前进
@property (nonatomic, readonly) BOOL canGoForward;
//是否支持左右手势前进或后退
@property (nonatomic) BOOL allowsBackForwardNavigationGestures;
//是否允许链接3d touch iOS9后
@property (nonatomic) BOOL allowsLinkPreview;
//设置UserAgent iOS9后
@property (nullable, nonatomic, copy) NSString *customUserAgent;


WKNavigationDelegate里的方法简介


[Objective-C] 纯文本查看 复制代码
// 决定导航的动作,通常用于处理跨域的链接能否导航。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;
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
//接收到服务重定向时,会回调此方法或接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
//加载数据失败时,会回调
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
//web内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
//页面加载失败
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
//对于HTTPS的都会触发此代理,如果不要求验证,传默认就行
如果需要证书验证,与使用AFN进行HTTPS证书验证是一样的 
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;
//当 WKWebView 总体内存占用过大,页面即将白屏的时候,系统会调用上面的回调函数,我们在该函数里执行[webView reload](这个时候 webView.URL 取值尚不为 nil)解决白屏问题。在一些高内存消耗的页面可能会频繁刷新当前页面,H5侧也要做相应的适配操作。
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView;


WKUIDelegate方法简介


[Objective-C] 纯文本查看 复制代码
// 创建新的webview
// 可以指定配置对象、导航动作对象、window特性
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
//webview关闭时回调注意iOS9后
- (void)webViewDidClose:(WKWebView *)webView
////当把JS返回给控制器,然后弹窗就是这样设计的
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
//// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
//支持预览 也就是3D Touch
- (BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo API_AVAILABLE(ios(10.0));
- (nullable UIViewController *)webView:(WKWebView *)webView previewingViewControllerForElement:(WKPreviewElementInfo *)elementInfo defaultActions:(NSArray<id <WKPreviewActionItem>> *)previewActions API_AVAILABLE(ios(10.0));
- (void)webView:(WKWebView *)webView commitPreviewingViewController:(UIViewController *)previewingViewController API_AVAILABLE(ios(10.0));



与原生交互

通过各种配置后就可以显示web,另外就需要交互了.
先说oc->js传递参数


[Objective-C] 纯文本查看 复制代码
//可以直接执行js代码
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
//例:直接获取到title
[self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
NSLog(@"title:%@", title);
}];


oc向js传递参数相对比较简单,js->oc相对麻烦一些


[Objective-C] 纯文本查看 复制代码
//直接添加一个handle,和name.这样js就可以通过window.webkit.messageHandlers.<name>.postMessage(<messageBody>)获取和传递 - (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;


例如:

[Objective-C] 纯文本查看 复制代码
[controller addScriptMessageHandler:self name:@"takeUserImage"];
js则可以通过方法传递数据
window.webkit.messageHandlers.takeUserImage.postMessage(null);


然后我们可以在代理方法获取数据


[Objective-C] 纯文本查看 复制代码
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@", message);
if ([message.name isEqualToString:@"takeUserImage"]) {

}
}


以上基本完成了web的大部分功能.但是在实际运用时会遇到各种问题和坑等着我们来填.
自己在实际中遇到的问题进行了总结:
首先是与js交互时我们用到


[Objective-C] 纯文本查看 复制代码
[controller addScriptMessageHandler:self name:@"takeUserImage"];


[Objective-C] 纯文本查看 复制代码
如果我们直接这样写,dealloc不会走.
解决方法就是新建一个Controller来完成WKScriptMessageHandler代理方法:


[Objective-C] 纯文本查看 复制代码
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if ([self.delegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
[self.delegate userContentController:userContentController didReceiveScriptMessage:message];
}
}


这样我们在dealloc中不要忘记


[Objective-C] 纯文本查看 复制代码
[self.userContentController removeScriptMessageHandlerForName:@"takeUserImage"];




1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
 楼主| 发表于 2018-12-29 15:42:51 | 显示全部楼层
使用本地图片问题

使用本地图片,例如我们在需要选取相册的图片提供给js使用.我们可以用如下的方式
1.将图片上传到公司服务器,然后得到图片地址后将地址直接传给js使用.这种方式感觉比较笨.
2.将图片保存到本地的沙盒中,注意必须是tmp目录不然还是获取不到,如下

[Objective-C] 纯文本查看 复制代码
NSString *path_document = NSHomeDirectory();
    NSString *imagePath = [path_document stringByAppendingString: @"/tmp/mychoose.jpg"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.25);
    [imageData writeToFile:imagePath atomically:YES];


这样js就可以通过imagePath来获取本地图片了
3.还可以将图片转为data然后转为base64直接传给js使用具体可见demo
以上解决了使用本地图片的问题
 楼主| 发表于 2018-12-29 15:45:36 | 显示全部楼层
Cookie管理问题

这个应该是WKWebView最大的问题了,这个问题会让不少人放弃使用.
总结来说设置Cookie有3种方式
1.request设置Cookie

[Objective-C] 纯文本查看 复制代码
[request setValue: @"hq_http_usertoken=GojvvmpfnXXAQ6/HxBfMIQFJhWXOBYQfzhWCHpRABtI=;domain=hq-app-dev.io" forHTTPHeaderField: @"Cookie"];


2.WKUserScript设置

[Objective-C] 纯文本查看 复制代码
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie='hq_http_usertoken=GojvvmpfnXXAQ6/HxBfMIQFJhWXOBYQfzhWCHpRABtI=;domain=hq-app-dev.zhongan.io;path=/'; "injectionTime: WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];


3.直接js注入

[Objective-C] 纯文本查看 复制代码
[webView evaluateJavaScript:@"document.cookie = 'hq_http_usertoken=GojvvmpfnXXAQ6/HxBfMIQFJhWXOBYQfzhWCHpRABtI=;domain=hq-app-dev.zhongan.io;path=/'" completionHandler: ^(id result, NSError *error) {
        NSLog(@"%@%@",result,error);
    }];


发表于 2018-12-29 15:56:16 | 显示全部楼层
强烈支持楼主ing……
发表于 2018-12-29 16:37:10 | 显示全部楼层
真是难得给力的帖子啊。
发表于 2018-12-29 16:47:18 | 显示全部楼层
我只是路过打酱油的。
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-3-28 18:54

© 2014-2021

快速回复 返回顶部 返回列表