WKWebView

WKWebView是iOS8之后的网页加载组件,用来加载网页等

WKWebView的基本属性和方法

(1) WKWebViewConfiguration

WebView的基础配置属性

(2) WKProcessPool *processPool

这个是web内容加载池,同一个应用,不同WKWebView之间的cookie同步,可以通过使用同一个WKProcessPool实现cookie的同步。

(3) WKPreferences *preferences

这是web的偏好设置,还可以对web进行设置

这是他的三个属性
minimumFontSize //最小的文字大小,默认为0
javaScriptEnabled //是否可以进行js交互,默认为YES javaScriptCanOpenWindowsAutomatically //是否可以不通过用户的交互打开窗口,默认在iPhone是NO,在Mac上是YES

(4) WKUserContentController *userContentController

内容交互控制器,这个可以通过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

这个对象可以用于JS交互,将其注入到userContentController中,可以将其进行交互

// 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 *websiteDataStore

iOS9以后才能用这个类,是代表webView不同的数据类型,cookies、disk、memory caches、WebSQL、IndexedDB数据库和本地存储。

//默认的存储
+ (WKWebsiteDataStore *)defaultDataStore;

//暂时性的存储
+ (WKWebsiteDataStore *)nonPersistentDataStore;

//是否是永久的存储
@property (nonatomic, readonly, getter=isPersistent) BOOL persistent;

//所有的web存储类型
+ (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;
//删除缓存

//指定要删除的web的类型,这里指定的是所有的web的类型

NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];

//或者你可以单独的指定类型
//types的类型有

/*

 WKWebsiteDataTypeDiskCache,

 WKWebsiteDataTypeOfflineWebApplicationCache,

 WKWebsiteDataTypeMemoryCache,

 WKWebsiteDataTypeLocalStorage,

 WKWebsiteDataTypeCookies,

 WKWebsiteDataTypeSessionStorage,

 WKWebsiteDataTypeIndexedDBDatabases,

 WKWebsiteDataTypeWebSQLDatabases

 */

//NSSet *websiteDataTypes = [NSSet setWithArray:types];


//指定一个时间,从哪个时间段的缓存开始删除

NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

//执行删除代码

[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

    //删除后执行操作

}];
(7) WKWebsiteDataRecord *websiteDataRecord

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

// 通常是域名
@property (nonatomic, readonly, copy) NSString *displayName;

// 存储的数据类型集
@property (nonatomic, readonly, copy) NSSet<NSString *> *dataTypes;
(8) BOOL suppressesIncrementalRendering

是否等到缓存写入到内存中再渲染,默认是NO

(9) BOOL allowsInlineMediaPlayback

网页的视频是否支持在webView的视图中直接播放

(10) WKNavigationDelegate

webView的代理,处理各种回调方法

 // 决定导航的动作,通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制,不允许跨域,因此我们要对不能跨域的链接单独处理。但是,对于Safari是允许跨域的,不用这么处理。
 // 这个是决定是否Reques,在发送请求之前,决定是否跳转
 - (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
(11) WKNavigationResponse

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

// 是否是main frame
@property (nonatomic, readonly, getter=isForMainFrame) BOOL forMainFrame;

// 获取响应response
@property (nonatomic, readonly, copy) NSURLResponse *response;

// 是否显示MIMEType
@property (nonatomic, readonly) BOOL canShowMIMEType;```

##### (12) 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;


##### (13) WKUIDelegate

// 创建新的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;
    
##### (14) 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


##### (15) 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


##### (16) estimatedProgress
加载的进度,有这个之后就不用自己写假的进度条了


## 配置JS和WebView交互

##### (1) 在WKUserContentController中注入JS用户交互

**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);
    }
    }


**JS端**

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


##### (2) WKUIDelegate代理方法

与JS的alert、confirm、prompt交互,我们希望用自己的原生界面,而不是JS的,就可以使用这个代理类来实现。
在WKWebview中,js的alert是不会出现任何内容的,你必须重写WKUIDelegate委托的 `runJavaScriptAlertPanelWithMessage message` 方法,自己处理alert。类似的还有Confirm和prompt也和alert类似,这里我只以alert为例。

(1) 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);

}


(2) 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);

}


(3) 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];
    }


## 补充

##### 禁用UIWebView页面双击/捏合手势放大缩小页面的功能

在加载完WebView之后,添加一段JS到WebView

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />


  标签里的scale 值就是页面的初始化页面大小< initial-scale >和可伸缩放大最大< maximum-scale >和最小< minimum-scale >的的倍数。如果还有别的需求可自行设置,如果都为1表示初始化的时候显示为原来大小,可缩放的大小都为原来的大小<即不可缩放>。

##### 禁用页面元素

// 禁用 页面元素选择

[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
    
}];

// 禁用 长按弹出ActionSheet

[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
    
}];

##### 基础学习WKWebView(整个WebView的文章)
http://www.jianshu.com/p/433e59c5a9eb

##### WKWebView的那些坑

http://mp.weixin.qq.com/s/rhYKLIbXOsUJC_n6dt9UfA

<br>
>参考链接:
>http://www.jianshu.com/p/7bb5f15f1daa
>http://www.jianshu.com/p/403853b63537
>http://www.jianshu.com/p/99c3af6894f4
>http://www.jianshu.com/p/d2c478bbcca5
>http://nshipster.cn/wkwebkit/
>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • 1、加载网页 WKWebView *webView = [[WKWebView alloc] initWithFr...
    LearningCoding阅读 2,990评论 0 2
  • 前言 关于UIWebView的介绍,相信看过上文的小伙伴们,已经大概清楚了吧,如果有问题,欢迎提问。 本文是本系列...
    CoderLF阅读 8,856评论 2 12
  • 前言 上一篇专门讲解了WKWebView相关的所有类、代理的所有API。前篇文章地址:http://blog.cs...
    iwolfox阅读 1,062评论 1 1
  • 今天翻印象笔记,偶尔看到一条之前和朋友的聊天记录,当时颇有感触顺手截图留存。今日再看,发现一些彼时未发现的细节。 ...
    夜航大象阅读 396评论 0 0
  • 我现在什么也不想做 只想将你捧在手心 我像一只久在囚笼的鸟 早已忘记飞行 当囚笼打开 我没有欣喜 只有恐惧 恐惧这...
    圣石上的你和我阅读 121评论 0 0