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.lxweimin.com/p/433e59c5a9eb

##### WKWebView的那些坑

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

<br>
>參考鏈接:
>http://www.lxweimin.com/p/7bb5f15f1daa
>http://www.lxweimin.com/p/403853b63537
>http://www.lxweimin.com/p/99c3af6894f4
>http://www.lxweimin.com/p/d2c478bbcca5
>http://nshipster.cn/wkwebkit/
>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容

  • 1、加載網頁 WKWebView *webView = [[WKWebView alloc] initWithFr...
    LearningCoding閱讀 3,143評論 0 2
  • 前言 關于UIWebView的介紹,相信看過上文的小伙伴們,已經大概清楚了吧,如果有問題,歡迎提問。 本文是本系列...
    CoderLF閱讀 9,010評論 2 12
  • 前言 上一篇專門講解了WKWebView相關的所有類、代理的所有API。前篇文章地址:http://blog.cs...
    iwolfox閱讀 1,117評論 1 1
  • 今天翻印象筆記,偶爾看到一條之前和朋友的聊天記錄,當時頗有感觸順手截圖留存。今日再看,發現一些彼時未發現的細節。 ...
    夜航大象閱讀 410評論 0 0
  • 我現在什么也不想做 只想將你捧在手心 我像一只久在囚籠的鳥 早已忘記飛行 當囚籠打開 我沒有欣喜 只有恐懼 恐懼這...
    圣石上的你和我閱讀 131評論 0 0