1,导入
#import <WebKit/WebKit.h>
2,实现代理
<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
3,
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.preferences = [[WKPreferences alloc]init];
// config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.userContentController = [[WKUserContentController alloc]init];
config.processPool = [[WKProcessPool alloc]init];
_wkweb1 = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavHeight, SCREEN_WIDTH, 250) configuration:config];
_wkweb1.UIDelegate = self;
_wkweb1.navigationDelegate = self;
[self.view addSubview:_wkweb1];
NSString *path = [[NSBundle mainBundle] pathForResource:@"home.html" ofType:nil];
[_wkweb1 loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
//注册JS协议方法,也就是OC通知JS给这个名字叫GetNo传值操作
[config.userContentController addScriptMessageHandler:self name:@"GetNo"];
4,实现代理方法
#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
if (webView == self.wkweb1) {
NSString *str = [self GetJSONStr];
NSString * jsStr=[NSString stringWithFormat:@"myFun('%@')",str];
NSLog(@"jsStr==%@",jsStr);
[self.wkweb1 evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
// NSLog(@"HOme:%@==Home:%@",result,error);
}];
}
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"message.name=%@==message.body=%@",message.name,message.body);
if ([message.name isEqualToString:@"GetNo"]) {
NSLog(@"message.name=%@==message.body=%@",message.name,message.body);
[self AFNworing2:message.body];
}
}
5.JS代码
image.png
6.特别要注意的事。一定要切记。文件拿齐全。 image.png
网友评论