美文网首页
原生与H5交互

原生与H5交互

作者: _RG | 来源:发表于2019-12-27 14:01 被阅读0次

本文讲述使用<JSExport>协议进行H5和webView的交互,包含原生向JS传参和JS向原生传递参数

创建webVIew,获取jscontext,设置桥接对象

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
        _webView.delegate = self;
        NSString *path = [NSBundle.mainBundle pathForResource:@"indexTwo" ofType:@"html"];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL fileURLWithPath:path]];
        [_webView loadRequest:request];
    }
    return _webView;
}

- (RGBridge *)bridge {
    if (!_bridge) {
        _bridge = [RGBridge new];
    }
    return _bridge;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView  {
    
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
  //指定与JS的桥接对象
    self.context[@"RGBridge"] = self.bridge;
    [self.context setExceptionHandler:^(JSContext * context, JSValue * value) { //前端调用出错
        NSLog(@"前端函数调用报错%@",[value·· toObject]);
    }];
}

setExceptionHandler当前端函数调用报错时,此方法的block会被触发

@protocol RGJSExport <JSExport>


JSExportAs(location, - (void)locationWithParams:(JSValue *)params callback:(JSValue *)callback);

JSExportAs(share, - (void)shareWithParams:(JSValue *)params callback:(JSValue *)callback);

@end

@interface RGBridge : NSObject <RGJSExport>

@end

@implementation RGBridge

- (void)locationWithParams:(JSValue *)params callback:(JSValue *)callback {
   NSDictionary *dic = [params toDictionary];
   NSLog(@"获取前端发过来的定位参数params = %@",dic);
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       //假设经过2秒后定位成功,将定位到的结果返回给前端JS
       [callback callWithArguments:@[@YES,@6]];
   });
}

- (void)shareWithParams:(JSValue *)params callback:(JSValue *)callback {
   NSDictionary *dic = [params toDictionary];
   NSLog(@"获取前端分享参数params = %@",dic);
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [callback performSelectorOnMainThread:@selector(callWithArguments:) withObject:@[@YES,@"分享完成"] waitUntilDone:NO];
   });
   
}

@end

这里在桥接的协议里面定义了两个与JS交互的方法locationshare, 当前端用的JS里面触发RGBridge . share或者RGBridge . location时,iOS里面会调用对应的方法, 并接受参数paramscallback

前端JS可以这样写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>


        var RGBridge = {
            share : function(params,callback){
            },
            printTest : function () {

            }
        };

        var requestAppLocation = function () {
            console.log("测试");

            var params = {
                title : "你好",
                age : 18
            };

            RGBridge.share(params,function (a,b) {
                RGBridge.printTest();

                if (a){
                    alert(b);
                } else {
                    alert("错误");
                }
                // console.log(a+b);
            });
        };

    </script>


</head>
<body>

<button onclick=requestAppLocation()>测试按钮Two</button>

</body>
</html>

此时的callback就是原生操作后给H5里面的回调,可以使用callWithArguments给回调进行传参
例如
[callback callWithArguments:@[@YES,@6]];

相关文章

网友评论

      本文标题:原生与H5交互

      本文链接:https://www.haomeiwen.com/subject/ztsloctx.html