一、说明
最近在项目中用到了这块内容,虽然理解这其中的交互并不难,但初次接触很费劲。为了以后开发更简单,今天特记录下自己的理解和认识,一哈哈哈,大神勿喷!
二、用Xcode新建一个HTML5文件 ,写一些简单的标签语言
<head>
<meta charset="UTF-8">
<title>冷武橘的网页</title>
<!-- 跳转到百度-->
<script>
function jumpurl()
{
location.href='https://www.baidu.com';
}
</script>
<!-- JS端调用OC的方法-->
<script>
function jump() {
}
</script>
</head>
<!--身体标签-->
<body>
<button style="background:yellow;width:250px;height:150px;font-size:40px"onclick="jumpurl()" >点击跳转到百度</button><br />
<button style="background:red;width:250px;height:150px;font-size:40pxonclick="jump()">点击跳转到原生界面</button><br />
<button style="background:green;width:250px;height:150px;font-size:40px"onclick="jump()">测试二</button>
</body>
</html>
三、加载新建的HTML5文件
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController (){
WKWebView*webview;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"我是一个H5页面";
webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 375, 667)];
[self.view addSubview:webview];
[webview sizeToFit];
//加载本地html中的网页
[webview loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle]URLForResource:@"HLT" withExtension:@"htm"]]];
}
这时运行一下,你会看到很丑的一个网页,哈哈,够用就好。
四、交互开始
4.1、JS调用OC
简单:需求点击网页的红色按钮跳转到下一界面
a. JS端的操作:
在上面 HTML5 function jump() { }里添加以下代码:window.webkit.messageHandlers.webApp.postMessage(message);
!-- WKwebview JS端调用app-->
<script>
function jump() {
//message要发送的数据可以是多种类型,只支持NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull类型。
var message = {"method":"管理平台"};
//message要发送的数据可以是多种类型,只支持NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull类型。
window.webkit.messageHandlers.webApp.postMessage(message);
// window.webkit.messageHandlers.app端注册的名称.postMessage(参数)
//webApp为app端注册的名称,由html5和ios端共同约定,名字随便起
}
</script>
以上代码的含义就是: 点击红色按钮后,向webkit发送一个带参数的消息,通知ios端去执行一些事情。
b. IOS端的操作:监听网页中按钮的点击,并调用本地的方法
注册监听
#import "ViewController.h"
#import "SecViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKScriptMessageHandler>{
WKWebView*webview;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"我是一个H5页面";
//1.初始化webview的一个配置,配置与wkwebview的一个链接,为初始化一个可交互的webview做准备
WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];
//2.注册一个名为hybridDemo的handler对象,名称要与js端一致。
[config.userContentController addScriptMessageHandler:self name:@"webApp"];
/* js代码:window.webkit.messageHandlers.webApp.postMessage(message)中的webApp一定要与name一致,
*/
//3.初始化一个带有配置的webview
webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 375, 667) configuration:config ];
[self.view addSubview:webview];
//4.加载webview
[webview loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle]URLForResource:@"HLT" withExtension:@"htm"]]];
}
方法实现
//监听js的调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSDictionary *dic = message.body;
NSString *method = [dic objectForKey:@"method"];
if ([method isEqualToString:@"管理平台"]) {
SecViewController *secontoller=[[SecViewController alloc]init];
[self.navigationController pushViewController:secontoller animated:YES];
}
}
只要js端发送一个消息,实现这个方法就可以接收到消息,根据不同的参数值,去实现不同的方法,从而实现两者的交互
4.2、OC调用js
OC调用js比较简单,可以直接调用- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//OC调用js方法,直接传入js的方法名,可以带参数也可以不带参数
[webview evaluateJavaScript:@"show()"completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",response);
}];
[webview evaluateJavaScript:@"jump('哈喽','你好')"completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",response);
}];
}
4.3 wkwebview弹出提示框
wkwebview加载出来的网页,对于html5 的提示框(alter,confirm,prompt)并不能直接显示出来,需要根据需要实现以下三个代理方法,监听获得message,借助于原生的UI显示出来,注意遵守WKUIDelegate协议,webview.UIDelegate=self;
#pragma mark -监听 js alter()
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"确认");
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark -监听 js confirm()
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
// DLOG(@"msg = %@ frmae = %@",message,frame);
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark -监听 js prompt()
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text?:@"");
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
网友评论