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

查看:127
本文介绍了如何使用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.

有没有办法实现这个?

推荐答案

没有直接方式要做到这一点,但你可以使用 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天全站免登陆