如何使用Javascript与Objective-c代码进行通信?

发布于 2024-10-09 01:31:35 字数 149 浏览 0 评论 0原文

在本机 iPhone 应用程序中,我使用 UIWebView 加载网页。

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

有没有办法实现这个?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡看悲欢离合 2024-10-16 01:31:35

没有“直接”的方法来做到这一点,但是您可以利用UIWebViewDelegate并捕获具有自定义方案的链接,因此在您的标记中,您可以编写一些内容像这样:

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

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

- (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;
}

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>

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文