在日常的开发中,OC与H5的混合开发已经很普遍了,OC与H5的交互也就在所难免了,下面就先来总结一下原生的方法。
H5调用OC
用WKWebView的话,首先得添加代理<WKNavigationDelegate>,设置当前代理navigationDelegate,然后实现下面的代理方法;
原理其实就是操作H5的时候会发送一次请求,我们在代理方法里拦截请求,然后拿到一些参数,来做响应的操作。
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString *hostName = navigationAction.request.URL.absoluteString;
// url的协议头是自己规定,和H5协商一致就行,另外urlHeader中的大写会变小写
NSRange range = [hostName rangeOfString:@"urlheader://"];
NSUInteger loc = range.location;
if (loc != NSNotFound) {
// 方法名
NSString *method = [hostName substringFromIndex:loc + range.length];
// 转成SEL
SEL sel = NSSelectorFromString(method);
if ([self respondsToSelector:sel]) {
[self performSelector:sel withObject:nil];
}
decisionHandler(WKNavigationActionPolicyCancel);
}else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
然后我在H5l里给按钮添加两个这样的事件:
function fn_call() {
// 调用OC中call方法
window.location.href = 'urlHeader://call';
}
function fn_open_camera() {
// 调用OC中openCamera方法
window.location.href = 'urlHeader://openCamera';
}
然后在原生里就可以拦截到然后调用这个两个方法了:
{
NSLog(@"call++++");
}
- (void)openCamera
{
NSLog(@"openCamera++++");
}
UIWebView就在这个代理方法了里操作:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
OC调用H5
这个就简单多了,直接调用webView的evaluateJavaScript方法执行JS的代码即可;
NSString *jsStr = @"fn_open_camera();";
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result,error);
}];
UIWebView则用这个方法
stringByEvaluatingJavaScriptFromString
补充
JavaScriptCore也是一个不错的原生框架,但是只能跟UIWebView搭配使用,而UIWebView在ios12以后已经被废弃了,所以就不说了。那就来看看切换到WKWebView的代替方案,那就是WKMessageHandler。
1.我就直接贴全部代码了,首先我们的给WKWebView添加一个configuration,其中JScript参数来控制web的大小自适应当前屏幕大小的,不用太在意,而WKUserContentController是用来监听JS方法调用的。
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
NSString *JScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:JScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
configuration.userContentController = wkUController;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
self.title = @"WKMessageHandler";
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(didClickRightAction)];
self.navigationItem.rightBarButtonItem = rightItem;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 添加JS的方法的调用处理
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"methodName"];
}
-(void)viewWillDisappear:(BOOL)animated {
// 添加JS的方法的调用处理,必须销毁,否则会造成循环引用
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"methodName"];
}
- (void)didClickRightAction{
NSLog(@"didClickRightAction");
NSString *jsStr = @"showAlert('这是来自OC的参数')";
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
}
#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@----%@",message.name,message.body);
// 通过name来做判断 做相应的处理
}
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - dealloc
- (void)dealloc{
NSLog(@"dealloc:走了");
}
下面是JS的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OC与JS交互</title>
<script>
function loadURL(url) {
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", url);
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
function showAlert(messgae){
alert('这是一个接收OC数据的一个弹框 \n'+messgae);
return "token";
}
function messgaeHandle(){
// ANDROID
window.webkit.messageHandlers.methodName.postMessage("这是来自JS的调用");
}
</script>
</head>
<body>
<input type="button" value="弹框" onclick="showAlert('hello JS')" /><br />
<input type="button" value="messgaeHandle" onclick="messgaeHandle()" /><br />
</body>
</html>
OC调用JS
- (void)didClickRightAction{
NSLog(@"didClickRightAction");
NSString *jsStr = @"showAlert('这是来自OC的参数')";
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
}
可以看到在JS里return一个参数,在OC里还可以拿到回调
打印
2018-11-06 17:46:34.969623+0800 test_WKMessageHandler[4231:1948196] didClickRightAction
2018-11-06 17:46:37.008732+0800 test_WKMessageHandler[4231:1948196] token----(null)
JS调用OC
在viewWillAppear里添加JS方法调用的处理,同时必须添加销毁操作,否则会造成循环引用
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 添加JS的方法的调用处理
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"methodName"];
}
-(void)viewWillDisappear:(BOOL)animated {
// 添加JS的方法的调用处理,必须销毁,否则会造成循环引用
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"methodName"];
}
然后实现WKScriptMessageHandler代理,然后在下面的方法里通过name来判断是哪个方法,从而做后续操作
#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@----%@",message.name,message.body);
// 通过name来做判断 做相应的处理
}
打印
2018-11-06 17:45:41.118480+0800 test_WKMessageHandler[4231:1948196] methodName----这是来自JS的调用