[英]Suggestions for how to communicate from JS running in a UIWebView to the hosting obj-c app?
I plan to have a shell iphone app with a uiwebview, with the bulk of my application running through javascript in the uiwebview. 我计划有一个带有uiwebview的shell iphone应用程序,我的应用程序的大部分都在uiwebview中通过javascript运行。
Now i know it's easy to communicate from the obj-c environment to the javascript environment by using stringByEvaluatingJavaScriptFromString, however is there a good recommended way of communicating from the javascript environment to the obj-c world? 现在我知道通过使用stringByEvaluatingJavaScriptFromString从obj-c环境到javascript环境的通信很容易,但是有一个很好的推荐方式从javascript环境到obj-c世界进行通信吗?
Thanks 谢谢
I always use an approach in which the app "navigates" to a special URL: 我总是使用应用程序“导航”到特殊URL的方法:
window.location = "myapp://somemessage/someargument";
And where the app catches this in the following function: 应用程序在以下功能中捕获此内容:
-(BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
if ( [[url scheme] isEqualToString:@"myapp"] )
{
[self handleJSEvent:url];
return NO;
}
return YES;
}
Furthermore, depending on what you need, you could use some kind of event queue which you fetch using JSON.stringify(events)
, in response to a message sent to the app using the method described above. 此外,根据您的需要,您可以使用您使用
JSON.stringify(events)
获取的某种事件队列,以响应使用上述方法发送到应用程序的消息。 For communicating from app to js JSON is also very suitable. 对于从app到js的通信,JSON也非常合适。
If there is a standard or a standard way to do this, I clearly missed it. 如果有标准或标准的方法来做到这一点,我显然错过了它。
There is a very nice method to call javascript inside of UIWebView: 在UIWebView中调用javascript有一个非常好的方法:
[webView stringByEvaluatingJavaScriptFromString:@"yourJSFunction('some_data');"];
call backs are best done as mentioned by MVDS through the Url: 如MVDS通过Url所述,最好完成回拨:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
I just created a library that will facilitate this communication for you largely using the method described by mvds and Ondrej. 我刚刚使用mvds和Ondrej描述的方法创建了一个为您提供便利的库。 Includes two-way communication, jQuery event-style, with optional JSON payloads with multiple listeners.
包括双向通信,jQuery事件样式,带有多个侦听器的可选JSON有效负载。 Check it out: https://github.com/tcoulter/jockeyjs
看看: https : //github.com/tcoulter/jockeyjs
也许通过更改url哈希?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.