WKWebView的簡單使用
簡單使用
初始化
#pragma mark - Getting With Setting
- (WKWebView *)webView {
if (!_webView) {
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_webView.backgroundColor = [UIColor whiteColor];
[_webView setUserInteractionEnabled:YES];
// 導(dǎo)航代理
_webView.navigationDelegate = self;
// 與webview UI交互代理
_webView.UIDelegate = self;
//加載網(wǎng)頁
NSURLRequest * urlReuqest = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:_urlStr]];
[_webView loadRequest:urlReuqest];
//監(jiān)聽屬性
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
return _webView;
}
WKNavigationDelegate
如果需要處理web導(dǎo)航操作,比如鏈接跳轉(zhuǎn)、接收響應(yīng)、在導(dǎo)航開始、成功、失敗等時要做些處理,就可以通過實現(xiàn)相關(guān)的代理方法:
#pragma mark - WKNavigationDelegate
// 請求開始前,會先調(diào)用此代理方法
// 與UIWebView的
// - (BOOL)webView:(UIWebView *)webView
// shouldStartLoadWithRequest:(NSURLRequest *)request
// navigationType:(UIWebViewNavigationType)navigationType;
// 類型,在請求先判斷能不能跳轉(zhuǎn)(請求)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString *hostname = navigationAction.request.URL.host.lowercaseString;
if (navigationAction.navigationType == WKNavigationTypeLinkActivated
&& ![hostname containsString:@".baidu.com"]) {
// 對于跨域,需要手動跳轉(zhuǎn)
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
// 不允許web內(nèi)跳轉(zhuǎn)
decisionHandler(WKNavigationActionPolicyCancel);
} else {
self.progressView.alpha = 1.0;
decisionHandler(WKNavigationActionPolicyAllow);
}
NSLog(@"%s", __FUNCTION__);
}
// 在響應(yīng)完成時,會回調(diào)此方法
// 如果設(shè)置為不允許響應(yīng),web內(nèi)容就不會傳過來
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
decisionHandler(WKNavigationResponsePolicyAllow);
NSLog(@"%s", __FUNCTION__);
}
// 開始導(dǎo)航跳轉(zhuǎn)時會回調(diào)
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
NSLog(@"%s", __FUNCTION__);
}
// 接收到重定向時會回調(diào)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
NSLog(@"%s", __FUNCTION__);
}
// 導(dǎo)航失敗時會回調(diào)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"%s", __FUNCTION__);
}
// 頁面內(nèi)容到達main frame時回調(diào)
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
NSLog(@"%s", __FUNCTION__);
}
// 導(dǎo)航完成時,會回調(diào)(也就是頁面載入完成了)
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
NSLog(@"%s", __FUNCTION__);
}
// 導(dǎo)航失敗時會回調(diào)
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
// 對于HTTPS的都會觸發(fā)此代理,如果不要求驗證,傳默認就行
// 如果需要證書驗證,與使用AFN進行HTTPS證書驗證是一樣的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
NSLog(@"%s", __FUNCTION__);
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
// 9.0才能使用,web內(nèi)容處理中斷時會觸發(fā)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
NSLog(@"%s", __FUNCTION__);
}
JavaScript交互處理
創(chuàng)建配置類及其偏好設(shè)置
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 設(shè)置偏好設(shè)置
config.preferences = [[WKPreferences alloc] init];
// 默認為0
config.preferences.minimumFontSize = 10;
// 默認認為YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默認為NO,表示不能自動通過窗口打開
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
// web內(nèi)容處理池
config.processPool = [[WKProcessPool alloc] init];
// 通過JS與webview內(nèi)容交互
config.userContentController = [[WKUserContentController alloc] init];
// 注入JS對象名稱AppModel,當(dāng)JS通過AppModel來調(diào)用時,
// 我們可以在WKScriptMessageHandler代理中接收到
[config.userContentController addScriptMessageHandler:self name:@"AppModel"];
//加載web
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
configuration:config];
[self.view addSubview:self.webView];
WKUIDelegate
與JS原生的alert、confirm、prompt交互,將彈出來的實際上是我們原生的窗口,而不是JS的。在得到數(shù)據(jù)后,由原生傳回到JS:
#pragma mark - WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
NSLog(@"%s", __FUNCTION__);
}
// 在JS端調(diào)用alert函數(shù)時,會觸發(fā)此代理方法。
// JS端調(diào)用alert時所傳的數(shù)據(jù)可以通過message拿到
// 在原生得到結(jié)果后,需要回調(diào)JS,是通過completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
NSLog(@"%s", __FUNCTION__);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調(diào)用alert" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:NULL];
NSLog(@"%@", message);
}
// JS端調(diào)用confirm函數(shù)時,會觸發(fā)此方法
// 通過message可以拿到JS端所傳的數(shù)據(jù)
// 在iOS端顯示原生alert得到Y(jié)ES/NO后
// 通過completionHandler回調(diào)給JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
NSLog(@"%s", __FUNCTION__);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調(diào)用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(@"%@", message);
}
// JS端調(diào)用prompt函數(shù)時,會觸發(fā)此方法
// 要求輸入一段文本
// 在原生輸入得到文本內(nèi)容后,通過completionHandler回調(diào)給JS
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
NSLog(@"%s", __FUNCTION__);
NSLog(@"%@", prompt);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調(diào)用輸入框" preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor redColor];
}];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[alert.textFields lastObject] text]);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
調(diào)用js
實現(xiàn)KVO處理方法,在loading完成時,可以調(diào)用web中的JS。這里只是簡單地執(zhí)行一段web中的JS函數(shù):
#pragma mark - 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) {
// 手動調(diào)用JS代碼
// 每次頁面完成都彈出來,大家可以在測試時再打開
NSString *js = @"callJsAlert()";
[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"response: %@ error: %@", response, error);
NSLog(@"call js alert by native");
}];
[UIView animateWithDuration:0.5 animations:^{
self.progressView.alpha = 0;
}];
}
}
js數(shù)據(jù)傳遞
// AppModel是我們所注入的對象
window.webkit.messageHandlers.AppModel.postMessage({body: response});
WKWebView使用中遇到的問題
1.關(guān)于緩存的問題
因為使用了WKWebView,后端的策劃人員換圖,iOS端沒有更新,然后google了好久,最終算是解決了這個問題。
首先,加載第一個頁面
_urlStr = @"https://www.baidu.com";
//設(shè)置緩存的請求策略和超時時間
NSURLRequest * urlReuqest = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:_urlStr] cachePolicy:1 timeoutInterval:30.0f];
[_webView loadRequest:urlReuqest];
這時能正常的顯示第一個頁面,及時更換了圖片也能正常的顯示。
但是在跳轉(zhuǎn)另一個URL時,不能設(shè)置緩存方式。。。這樣就造成了,如果你更換了圖片,并且之前你進入了這個頁面,就導(dǎo)致了你看到的是以前的頁面。我這里找到的處理的方式是在這個WKWebView調(diào)用dealloc方法時,把html頁面的緩存全部刪掉。以下是方法
//在ViewController銷毀時移除KVO觀察者,同時清除所有的html緩存
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
[self.webView removeObserver:self forKeyPath:@"title"];
[self clearCache];
}
/** 清理緩存的方法,這個方法會清除緩存類型為HTML類型的文件*/
- (void)clearCache {
/* 取得Library文件夾的位置*/
NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
/* 取得bundle id,用作文件拼接用*/
NSString *bundleId = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
/*
* 拼接緩存地址,具體目錄為App/Library/Caches/你的APPBundleID/fsCachedData
*/
NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
NSError *error;
/* 取得目錄下所有的文件,取得文件數(shù)組*/
NSFileManager *fileManager = [NSFileManager defaultManager];
// NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有該文件夾下所有文件的文件名及文件夾名的數(shù)組
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
/* 遍歷文件組成的數(shù)組*/
for(NSString * fileName in fileList){
/* 定位每個文件的位置*/
NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
/* 將文件轉(zhuǎn)換為NSData類型的數(shù)據(jù)*/
NSData * fileData = [NSData dataWithContentsOfFile:path];
/* 如果FileData的長度大于2,說明FileData不為空*/
if(fileData.length >2){
/* 創(chuàng)建兩個用于顯示文件類型的變量*/
int char1 =0;
int char2 =0;
[fileData getBytes:&char1 range:NSMakeRange(0,1)];
[fileData getBytes:&char2 range:NSMakeRange(1,1)];
/* 拼接兩個變量*/
NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
/* 如果該文件前四個字符是6033,說明是Html文件,刪除掉本地的緩存*/
if([numStr isEqualToString:@"6033"]){
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
continue;
}
}
}
}