iOS WKWebView学习笔记(一)

WebKit是在iOS8.0以后,提出的一个网页视图框架,视图渲染控件也有UIWebView,演变成了WKWebView,首先特别好的一点,就是灵活性比之前好很多,另外一个,渲染速度和性能比之前快。(目前还没亲自验证)

同时,核心类,也演变成了如下:

WKPreferences,用户偏好设置设置类,

1)可以设置最小的字体大小minimumFontSize,默认是0

2)是否允许JS交互javaScriptEnabled,是否允许在无交互的情况下,默认YES,

3)系统自动打开一个新的window窗口javaScriptCanOpenWindowsAutomatically,默认NO。这个属性主要是针对,JS方法中,window.open('新的链接')。参考文章https://blog.csdn.net/ioszhanghui/article/details/89368229。javaScriptCanOpenWindowsAutomatically在设置成YES的时候,javaScriptEnabled也必须设置成YES。同时,需要设置UIDelegate对象,在实现的时候,系统会调用,- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures。

使用javaScriptCanOpenWindowsAutomatically时,可能出现,点击无响应的bug,主要原因是WKWebView允许,创建多个WKWebVIew加载,跟HTML5中,新建一个窗口是一样的,也就是HTML5中,target='_blank'。解决办法,参考文章https://blog.csdn.net/ioszhanghui/article/details/89368400

WKProcessPool 进程池设置,

如果项目中创建多个WKWebView,想要这个几个WKWebView共享资源内容,比如Cookie内容,需要这个几个WKWebView公用一个WKProcessPool对象,默认,没创建一个WKWebView对象 都会创建一个WKProcessPool对象,而且WKProcessPool类没有对外提供属性,也没有提供方法。参考文章https://blog.csdn.net/ioszhanghui/article/details/89368864

WKUserContentController 主要是提供用户交互类,比如常见的js注入,原生和h5的点击交互处理。
//查看所有的注入的用户交互JS,这个可以重复注入。
@property (nonatomic, readonly, copy) NSArray<WKUserScript *> *userScripts;
//添加JS交互注入
- (void)addUserScript:(WKUserScript *)userScript;
//移除所有的JS交互注入
//移除所有的JS交互注入
- (void)removeAllUserScripts;
//注册和h5交互的标识 (1)需要WKScriptMessageHandler遵循代理,(2)需要和h5统一name标识
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
//移除和h5交互的标识
- (void)removeScriptMessageHandlerForName:(NSString *)name;

1)在原生端通过addScriptMessageHandler,添加代理和区别标示进行注册。
2)实现代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
3)h5端JS实现中,通过Window的方法
window.webkit.messageHandlers.testMessage(标示).postMessage({"code":"200","message":"成功"});

WKScriptMessage 主要是交互的消息体类,属性name,是注册的标示,属性body是接收到的交互数据。

h5端相关的操作可以参考文章https://mp.csdn.net/postedit/89379171

UIDelegate的代理方法
//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
//输入框替换 等同于prompt();
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;

WKNavigationDelegate代理
//在发起请求之前 决定跳转不跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
//在收到响应之后,决定跳转不跳转
- (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;
//收到响应内容
- (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的授权认证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;

WKWebsiteDataStore WKWebView的缓存数据,包含内存缓存,硬盘缓存,cookie缓存,这个存储的是你用WKWebView加载过的所有缓存记录。WKWebsiteDataStore是以域名的格式进行缓存的。
/ * 磁盘缓存。 * /
WKWebsiteDataTypeDiskCache,
/ * 内存中的缓存 。* /
WKWebsiteDataTypeMemoryCache,
/ * HTML离线Web应用程序缓存。 * /
WKWebsiteDataTypeOfflineWebApplicationCache,
/ * Cookies 缓存。 * /
WKWebsiteDataTypeCookies,
/ * HTML会话存储。 * /
WKWebsiteDataTypeSessionStorage,
/ * HTML本地存储。 * /
WKWebsiteDataTypeLocalStorage 
/ * IndexedDB数据库。 * /
WKWebsiteDataTypeIndexedDBDatabases,
/ * WebSQL数据库。 * /
WKWebsiteDataTypeWebSQLDatabases

//默认的存储容器,是属于持久存储
+ (WKWebsiteDataStore *)defaultDataStore;
//临时的存储容器
+ (WKWebsiteDataStore *)nonPersistentDataStore;
//判断是不是持久存储
@property (nonatomic, readonly, getter=isPersistent) BOOL persistent;
//缓存数据的形式
+ (NSSet<NSString *> *)allWebsiteDataTypes;
//获取WKWebsiteDataStore的缓存数据 根据上面
- (void)fetchDataRecordsOfTypes:(NSSet<NSString *> *)dataTypes completionHandler:(void (^)(NSArray<WKWebsiteDataRecord *> *))completionHandler;
//删除WKWebsiteDataStore 根据删除的缓存 形式 数据存储的内容
- (void)removeDataOfTypes:(NSSet<NSString *> *)dataTypes forDataRecords:(NSArray<WKWebsiteDataRecord *> *)dataRecords completionHandler:(void (^)(void))completionHandler;
//删除缓存数据 从某个修改的日期开始之后的删除
- (void)removeDataOfTypes:(NSSet<NSString *> *)dataTypes modifiedSince:(NSDate *)date completionHandler:(void (^)(void))completionHandler;
//获取Http的Cookie缓存
@property (nonatomic, readonly) WKHTTPCookieStore *httpCookieStore API_AVAILABLE(macosx(10.13), ios(11.0));

WKWebsiteDataStore存储的数据样式是 WKWebsiteDataRecord ,
//缓存的域名 
@property (nonatomic, readonly, copy) NSString *displayName;
//存在的缓存的数据类型
@property (nonatomic, readonly, copy) NSSet<NSString *> *dataTypes;


WKBackForwardList  WKWebView加载的网页链接,所有加载过的页面记录。
//当前正在加载的页面 还没记录到backList
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *currentItem;
//可以返回的上一级网页页面
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *backItem;
//网页返回之后 可以前进的页面
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *forwardItem;
//根据你的索引获取 返回的上一页的页面项
- (nullable WKBackForwardListItem *)itemAtIndex:(NSInteger)index;
//所有的可返回页面项 只要加载过 没有后退 都在
@property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *backList;
//所有后退出来的页面
@property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *forwardList;

WKWebViewConfiguration WKWebView的配置类

//是不是所有的数据都加载到内存中 才开始渲染

@property (nonatomic) BOOL suppressesIncrementalRendering;

//是否允许HTML5内部播放

@property (nonatomic) BOOL allowsInlineMediaPlayback;

//是否允许自动播放 设置NO 不需要用户点击自动播放

@property (nonatomic) BOOL requiresUserActionForMediaPlayback

//是否可以AirPlay播放

@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay

WKWebView加载方法

//加载本地资源文件或者网络资源文件
- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
//加载本地的资源 iOS 9.0以后的方法
- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL API_AVAILABLE(macosx(10.11), ios(9.0));

但是这个方法,有一个ReadAccessToURL访问路径需要注意一下,需要把AccessToURL写到最公共的路径,保证资源都被加载,否则第一次加载的时候,会出不来:

NSString *pathA = "file:///path/to/abc/dirA/A.html";//需要加载的资源路径1
NSString *pathB = "file:///path/to/abc/dirB/B.html";//需要加载的资源路径2
NSString *pathC = "file:///path/to/abc/dirC/C.html";//需要加载的资源路径3


NSURL *url = [NSURL fileURLWithPath:pathA];

NSURL *readAccessToURL = [[url URLByDeletingLastPathComponent] URLByDeletingLastPathComponent];
 // readAccessToURL == "file:///path/to/abc/"[self.wk_webview loadFileURL:url allowingReadAccessToURL:readAccessToURL];
// then you want load  pathB
url = [NSURL fileURLWithPath:pathB];
// this will work fine
[self.wk_webview loadFileURL:url allowingReadAccessToURL:readAccessToURL];
//加载网页内容 网页内容转化成字符串 baseURL 必须要有 否则 网页中的相对路径内容无法加载。
 - (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
//加载网页消息  data网页的二进制数据 数据类型 MIMEType比如网页类型:text/html  characterEncodingName内容编码 utf-8 baseURL 资源的相对路径
- (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL

WKWebView执行JS

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

//允许执行边缘手势返回

@property (nonatomic) BOOL allowsBackForwardNavigationGestures;

//UserAgent设置

@property (nullable, nonatomic, copy) NSString *customUserAgent

//设置链接预览功能 默认NO 需要长按预览

@property (nonatomic) BOOL allowsLinkPreview API_AVAILABLE(macosx(10.11), ios(9.0));

//重新加载 会从服务器重新加载一份 跟本地缓存比较 如果有变化 加载请求的内容

- (nullable WKNavigation *)reloadFromOrigin;

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值