OC与JS之间的相互调用

OC调用JS

的时候是通过UIWebView的的

- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

方法实现的.这个方法想UIWebView传递有单需要执行的JS文件最后获得执行结果.

注意:该方法会同步返回一个字符串,因此是一个同步方法,可能会阻塞UI。


JS调用OC
没有直接的API, 但由于在UIWebView内发起的网络请求都会触发delegate的回调.可以通过delegate函数
  (

     - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType: (UIWebViewNavigationType)navigationType

)在原声界面得到通知.这样我们可以在UIWebView内发起一个特殊的网络请求,请求加载的网址通常不是真实的地址,地址常常类似:gap://Methodname?argument.

于是在UIWebView的delegate中,只要发现是gap:开头的地址,就不进行内容的加载,转而进行相应的调用逻辑.

还有另一种方法,

就是iOS7以后 apple添加了一个新的库JavaScriptCore,用来做JS交互,因此JS与原生OC交互也变得简单了许多。

第一种方法
举例HTML部分

    <html>

    <header>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script type="text/javascript">

    function showAlert(message){

        alert(message);

    }

    

    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 就没用了,所以把它从 dom 上移除掉

        iFrame.parentNode.removeChild(iFrame);

        iFrame = null;

    }

    function firstClick() {

        loadURL("firstClick://shareClick?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");

    }

    </script>

    </header>

    

    <body>

    <h2> 这里是第一种方式 </h2>

    <br/>

    <br/>

    <button type="button" οnclick="firstClick()">Click Me!</button>

    

    </body>

    </html>


在oc的代理方法中

#pragma mark - UIWebViewDelegate

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

    {

        NSURL * url = [request URL];

        if ([[url scheme] isEqualToString:@"firstclick"]) {

            NSArray *params =[url.query componentsSeparatedByString:@"&"];

            

            NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];

            for (NSString *paramStr in params) {

                NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];

                if (dicArray.count > 1) {

                    NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

                    [tempDic setObject:decodeValue forKey:dicArray[0]];

                }

            }

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"这是OC原生的弹出窗" delegate:selfcancelButtonTitle:@"收到" otherButtonTitles:nil];

            [alertView show];

            NSLog(@"tempDic:%@",tempDic);

            return NO;

        }

        

        return YES;

    }


注意:1. JS中的firstClick,在拦截到的url scheme全都被转化为小写。
2.html中需要设置编码,否则中文参数可能会出现编码问题。
3.JS用打开一个iFrame的方式替代直接用document.location的方式,以避免多次请求,被替换覆盖的问题。


第二种方法

首先导入JavaScriptCore然后在OC中获取JS的上下文


JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

再然后定义好JS需要调用的方法,例如JS要调用share方法:

则可以在UIWebView加载url完成后,在其代理方法中添加要调用的share方法:


- (void)webViewDidFinishLoad:(UIWebView *)webView

{

    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    //定义好JS要调用的方法, share就是调用的share方法名

    context[@"share"] = ^() {

        NSLog(@"+++++++Begin Log+++++++");

        NSArray *args = [JSContext currentArguments];

        

        dispatch_async(dispatch_get_main_queue(), ^{

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:selfcancelButtonTitle:@"收到" otherButtonTitles:nil];

            [alertView show];

        });

        

        for (JSValue *jsVal in args) {

            NSLog(@"%@", jsVal.toString);

        }

        

        NSLog(@"-------End Log-------");

    };

}

注意:

可能最新版本的iOS系统做了改动,现在(iOS9Xcode 7.3,去年使用Xcode 6 iOS 8没有线程问题)中测试,block中是在子线程,因此执行UI操作,控制台有警告,需要回到主线程再操作UI

其中相对应的html部分如下:


<html>

<header>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">


function secondClick() {

    share('分享的标题','分享的内容','图片地址');

}


function showAlert(message){

    alert(message);

}


</script>

</header>


<body>

<h2> 这里是第二种方式 </h2>

<br/>

<br/>

<button type="button" οnclick="secondClick()">Click Me!</button>


</body>

</html>

JS部分确实要简单的多了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值