调用Objective-C函数时将值返回到JavaScript [英] Returning values to JavaScript when calling an Objective-C function

查看:62
本文介绍了调用Objective-C函数时将值返回到JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 WebViewJavascriptBridge 来桥接iOS应用程序中的Objective-C和JavaScript。它工作得很好,但它不支持从调用的本机Objective-C函数返回调用JavaScript代码的值。

I've been using WebViewJavascriptBridge to bridge Objective-C and JavaScript in an iOS application. It works great but it lacks support for returning values to the calling JavaScript code from the called native Objective-C function.

我很确定Cordova(PhoneGap)可以在某种程度上回调,但我一直很难尝试理解底层机制是如何工作的。

I'm pretty sure that Cordova (PhoneGap) does that in some way with callbacks but I've been having a hard time trying to understand how the underlying mechanics work.

有没有人遇到同样的问题并设法找到解决方案?

Is there anyone who's had the same problem and that managed to find a solution?

推荐答案

如果你的意思是返回,因为你的JS调用者会看到调用返回的结果,我不知道该怎么做。我怀疑它需要一个JS中没有的线程操作。相反,您可以重新编码JS端逻辑以创建结果处理函数。在伪代码中:

If you mean, "return" in the sense that your JS caller will see the results as returned from the call, I don't know how to do it. I suspect it would take a level of thread manipulation not available in JS. Instead, you can recode your JS side logic to create a result handler function. In pseudo code:

res = CallObjC(args);
work with res...

成为

CallObjC(args, function(res) { work with res...});

不可否认有点尴尬但习惯了 - 这是一种非常常见的模式。在内部,JS桥代码创建请求到回调函数的映射。当ObjC代码具有结果时,它使用WebView的stringByEvaluatingJavaScriptFromString来调用定位和调用回调的JS桥代码。

Admittedly a bit awkward but get used to it - it is a very common pattern. Internally, the JS bridge code creates a mapping of the request to the callback function. When the ObjC code has the result, it uses WebView's stringByEvaluatingJavaScriptFromString to call the JS bridge code that locates and invokes the callback.

@Richard - 对你发布的解决方案要小心一点。设置window.location以调用shouldStartLoadWithRequest可能会导致webview中丢失的功能以及丢失给ObjectiveC的消息。目前的做法是使用iframe并使用某种消息队列来缓冲消息。

@Richard - Be a bit careful with the solution you posted. Setting window.location to invoke shouldStartLoadWithRequest can result in both lost functionality in the webview and also lost messages to ObjectiveC. Current practice is to use an iframe and have some kind of message queue that can buffer up messages.

这篇关于调用Objective-C函数时将值返回到JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆