如何将UIWebView中运行的HTML事件发送到本地Objective-C代码?

我想要在iOS应用程序中集成一个完整的HTML框架(即HTML / CSS / JavaScript),并使UIWebView负责运行HTML内容,以便与本机Objective-C源代码的其余部分进行通信。

方向1:在UIWebView中从Objective-C到HTML

让剩余的源代码发送消息到HTML内容的方式非常简单:我可以在Objective-C方面调用stringByEvaluatingJavaScriptFromString:并以正确的方式实现JavaScript方法。

方向2:从UIWebView中的HTML到Objective-C

这是我无法弄清楚的方式。 我到目前为止唯一的想法是使我的应用程序本地Web服务器,并使HTML请求的东西。 但我不知道该怎么做,虽然我认为它可以是骨骼,因为我相信应用程序,如事情,VLC或1Password可能会使用这种function。

任何想法使这个方向2工作或任何新的angular度来使HTML内容中的事件发送到Objective-C代码是值得欢迎的。

我已经做了这个使用jQuery和UIWebViewDelegate:

JavaScript(jQuery手机):

 $("#bloodType").change(function() { url = $("#bloodType option:selected").text(); url = "donordialog:bloodTypeChanged(" + url + ")"; window.location = url; }); 

所以,生成的URL看起来像: donordialog:bloodTypeChanged(typeAB-)

在我的objc代码中:

 -(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *URL = [request URL]; if ([[URL scheme] isEqualToString:@"donordialog"]) { // now we need to figure out the function part NSString *functionString = [URL resourceSpecifier]; if ([functionString hasPrefix:@"bloodTypeChanged"]) { // the blood type has changed, now do something about it. NSString *parameter = [functionString stringByReplacingOccurrencesOfString:@"bloodTypeChanged" withString:@""]; // remove the '(' and then the ')' parameter = [parameter stringByReplacingOccurrencesOfString:@"(" withString:@""]; parameter = [parameter stringByReplacingOccurrencesOfString:@")" withString:@""]; // log the paramter, as I don't know what to do with it right now NSLog(@"%@", parameter); } return NO; } return YES; } 

这段代码是从我目前正在使用的一个项目中逐字复制的,并且可以validation这个工作。

我刚刚创build了一个库,将为您做这个。 它支持通过JSON在你的Web应用程序和iOS之间进行双向沟通,这很大程度上依赖于这种方法。 检查出来: https : //github.com/tcoulter/jockeyjs

你通常从JavaScript中回放的方式是打开一个虚构的URL(通过window.location ),然后实现UIWebViewDelegate-webView:shouldStartLoadWithRequest:navigationType:来忽略导航并处理需要做的事情。

(在Mac OS X WebKit中,您可以向网站提供具有JavaScriptfunction的Objective-C对象,但这在iOS中不可用)。

PhoneGap正是为此而构build的