如何使用 Javascript 与 Objective-c 代码进行通信? [英] How to use Javascript to communicate with Objective-c code?

查看:11
本文介绍了如何使用 Javascript 与 Objective-c 代码进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在原生 iPhone 应用程序中,我使用 UIWebView 来加载网页.

In a native iPhone app, I use a UIWebView to load a web page.

我想在网页中使用 JavaScript 与 Objective-C 代码进行通信,例如调用 Objective-C 代码中的函数.

I want to use JavaScript in the web page to communicate back with the Objective-C code, for example invoke a function in Objective-C code.

有什么方法可以实现吗?

Is there any way to implement this?

推荐答案

没有直接"的方法可以做到这一点,但您可以利用 UIWebViewDelegate 并捕获带有自定义方案的链接,因此在您的标记中,您可以编写如下内容:

There is no "direct" way to do this, but you could utilize the UIWebViewDelegate and trap a link with a custom scheme, so in your markup, you'd write something like this:

<a href="myapp://app_action?doSomething">Do Something</a>

然后,在您的 UIWebViewDelegate-webView:shouldStartLoadWithRequest:navigationType: 方法中,编写如下内容:

Then, in your UIWebViewDelegate's -webView:shouldStartLoadWithRequest:navigationType: method, write something like this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if([[[request URL] scheme] isEqualToString:@"myapp"]) { 
       SEL selector = NSSelectorFromString([[request URL] query]);
       if([self respondsToSelector:selector]) {
          [self performSelector:selector];
       } else {
          //alert user of invalid URL
       }
       return NO;
    }
    return YES;
}

这篇关于如何使用 Javascript 与 Objective-c 代码进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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