寫在前面,平復心態:
//治大國,若烹小鮮,以道蒞天下,其鬼不神。非其鬼不神,其神不傷人。非其神不傷人,圣人亦不傷人。夫兩不相傷,故德交歸焉。
心塞,wkweb遇到了一些問題,忙活半天找不到問題,解決過后卻發現很簡單,在下面標注:首先,如果之前用的是UIWebView的話,那么不僅iOS前段需要改動,web前段也需要改動。其次,如果之前是用的http轉https也有一些注意點。上代碼吧:
@interface SignUpInViewController ()<WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate>
//初始化頁面
- (void)initWKWebView
{
//進行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
//實例化對象
WKUserContentController* userContentController = [WKUserContentController new];
//調用JS方法
[userContentController addScriptMessageHandler:self name:@"login"];
configuration.userContentController = userContentController;
// configuration.preferences.javaScriptEnabled = YES;
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 0.0;
preferences.javaScriptEnabled = YES;
configuration.preferences = preferences;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
NSURL *fileURL = [NSURL URLWithString:@"https://www.tingting365.com/index11.html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:fileURL]];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
}
這是WKWebView的初始化,有兩個注意點1,WKUserContentController最好重新創建在進行賦值,其二:WKPreferences同理。代理方法不多贅述。
WKWeb和js交互原理網上很多,我這兒實現的方式就一行代碼[userContentControlleraddScriptMessageHandler:selfname:@"login"];這里js方法名就是@“login”。放入之后再代理方法里面進行回調和識別(加判斷,和login一樣),代碼如下
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
// message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
NSLog(@"body:%@",message.body);
if ([message.name isEqualToString:@"login"]) {
NSLog(@"??哈哈");
}
}
好了,我心塞的一點來了:我這兒https沒有做認證,搞了一個投機的方式:
- (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);
}
}
oc代碼很簡單,就是上面兩個代理方法就好了,js代碼也不麻煩,直接上代碼吧:
JS:login方法如下:
if(window.login){
// 我這兒需要的登錄回調方法,可用可不要。
window.login.call(window,swUser);
}else{
//alert("login 方法沒有為空")
}
//swUser就是call方法
//這一句一定要加,一定要加,一定要加
window.webkit.messageHandlers.login.postMessage(swUser);
17年7月26日更新:
有朋友問我,window.webkit.messageHandlers.login.postMessage(swUser);
已經加了,wkweb
的代理寫的也沒有問題,為什么didReceiveScriptMessage
代理方法不調用?
原因如下
// 這是固定格式,一定要注意。。'parameter'可替換但是不能省略,一定要傳參數,在與web協商的時候要注意,否則OC的didReceiveScriptMessage代理方法不會調用的
window.webkit.messageHandlers.ActionName.postMessage('parameter');