背景:公司的老項目,使用的是uiwebview,我也沒用過,第一次做混合開發(fā),所以想直接使用wkwebview去替換當前的uiwebview,畢竟性能上提升了4倍,還有很多亂七八糟的優(yōu)化等,廢話不多說。
1.首先wkwebview有三個代理方法WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate
2.wkwebview創(chuàng)建的時候可以寫配置
有一個屬性的集合,叫WKWebViewConfiguration
其中還有一些首選項的配置WKPreferences
例如我是這么創(chuàng)建的:
// wkwebview屬性的集合
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
// webview一些首選項的配置
WKPreferences *preferences = [[WKPreferences alloc]init];
// 在沒有用戶交互的情況下,是否允許js打開窗口,macOS默認是yes,iOS默認是no
preferences.javaScriptCanOpenWindowsAutomatically = YES;
// webview的最小字體大小
// preferences.minimumFontSize = 40.0;
configuration.preferences = preferences;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
3.加載網(wǎng)頁,本地加載和加載服務器網(wǎng)頁
1.加載本地網(wǎng)頁
將html與css和js拖進項目,使用藍色物理文件夾放入。
加載本地網(wǎng)頁,使用
[self.webView loadFileURL:htmlPathUrl allowingReadAccessToURL:folderPathUrl];
其中htmlPathUrl代表html的路徑
其中folderPathUrl代表存放js與css的路徑
只有這樣才能加載完整的網(wǎng)頁,否則你可能加載不出css樣式和js方法。
例如:
#pragma mark 加載url展示頁面
//加載本地網(wǎng)頁
-(void)loadUrl{
NSString *folderPath = [[NSBundle mainBundle] pathForResource:@"sdk" ofType:@""];
NSURL *folderPathUrl = [NSURL fileURLWithPath:folderPath];
NSString *htmlPath = [folderPath stringByAppendingString:@"/h5/index.html"];
NSURL *htmlPathUrl = [NSURL fileURLWithPath:htmlPath];
[self.webView loadFileURL:htmlPathUrl allowingReadAccessToURL:folderPathUrl];
}
當然,如果網(wǎng)頁有ajax請求,注意跨域問題。試試jsonp。這里就提一下,略過。
2.加載服務器網(wǎng)頁
這就沒什么好說的了。。直接加載就行。
例如:
-(void)loadUrl{
NSString *urlString = @"https://www.baidu.com";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[SdkTools requestSetHeader:request];
[self.webView loadRequest:request];
}
4.與js交互的方法怎么寫
這里就要說到代理方法了,還記得第一點寫的WKScriptMessageHandler這個代理么。就是用來交互的。
和uiwebview不一樣,wk不能使用JavaScriptCore這個框架。
1.首先你需要使用
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"方法名"];
用完記得寫remove
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"方法名"];
這里建議大家將add寫在viewWillAppear中
將remove寫在viewWillDisappear中,原因是防止循環(huán)引用。可能會有兄弟有疑問循環(huán)在哪,循環(huán)在self.webView.configuration.userContentController中的userContentController,詳細大家可以查一下。
2.js那邊怎么調(diào)用呢?如下
window.webkit.messageHandlers.方法名.postMessage(參數(shù));
3.oc如何接收?如下
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
}
使用這個代理方法接收js的調(diào)用,具體是調(diào)了哪個方法可以通過message.name分別,因為message.name就是方法名。而message.body則是參數(shù),是一個json字符串,經(jīng)過解析就可以使用了。
4.oc方法執(zhí)行完畢如何將結(jié)果回調(diào)傳給js?如下
NSString *jss = [NSString stringWithFormat:@"%@('%@')",js接收的方法名,oc傳遞給js的結(jié)果(是一個不含換行符不含空格的json字符串)];
[self.webView evaluateJavaScript:jss completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//正常時,result和error都為null
NSLog(@"result = %@,error = %@",result,error);
}];
5.ok,那么下面放出一個例子,如何進行交互:
//oc.m
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// 退出
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"exitSdk" ];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"exitSdk"];
#pragma mark - 與js交互入口
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"wx.body ------ %@",message.body);
NSLog(@"wx.name ------ %@",message.name);
if ([message.name isEqualToString:@"exitSdk"]) {
[self exitSdk];
}
}
#pragma mark - 函數(shù)回調(diào)給js
-(void) exitSdk{
NSDictionary *dicParam = @{@"key":@"value"};
NSString *jsParam = [SdkTools dictionaryToJsonString:dicParam];
NSString *jss = [NSString stringWithFormat:@"%@('%@')",js方法名,jsParam];
[self.webView evaluateJavaScript:jss completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result = %@,error = %@",result,error);
}];
}
5.alert怎么彈
可能有些原生開發(fā)的老哥不知道js咋打斷點或者因為一些原因不方便打斷點,一般都會用alert去彈窗,獲取自己希望知道的結(jié)果,uiwebview還好,一使用wkwebview之后發(fā)現(xiàn),臥槽,alert不彈窗了。
其實是有代理方法沒寫。
#pragma mark 彈窗展示
//只有一個確定按鈕實現(xiàn)這個代理方法
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
[alertCtrl addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alertCtrl animated:YES completion:nil];
}
當然,有多個按鈕的就有勞各位老哥自己查一下,我這里就不放了。
6.頁面加載情況
都知道有很多代理方法,大家搜一搜也都有,其中大部分是對的,不過加載失敗有很多都是寫的錯誤的,至少在我搜索的結(jié)果中發(fā)現(xiàn)有相當一部分是錯誤的。這里放兩個,一個是加載開始,還有一個是加載失敗。
#pragma mark - 頁面開始加載時調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"頁面開始加載時調(diào)用");
}
#pragma mark 頁面加載失敗
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error{
NSLog(@"頁面加載失敗");
}
7.加載不受信任的服務器證書
#pragma mark - 加載不受信任的服務器
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}
8.隱藏界面發(fā)現(xiàn)頂部少了20PX的uiview
WKWebView加載web頁面,隱藏導航欄,全屏顯示,發(fā)現(xiàn)頂部出現(xiàn)20px的空白。
解決方法:
iOS 7以上,iOS 11以下:
self.edgesForExtendedLayout = UIRectEdgeNone;
iOS 11對安全區(qū)域做了一些修改,以下方法是iOS 11新增方法。
iOS 11:
self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
寫在最后
其他應該也沒什么了,大家結(jié)合自己情況使用就好。畢竟聽說性能提升了至少4倍呢。還有一些iOS8有的bug,比如iOS8本地加載只能復制到tmp才能加載之類的東西,各位老哥就自己查一查,看一看,應該就能找到詳細的解決方法。
各位老哥開發(fā)愉快~