How to use Javascript to communicate with Objective-c code?(如何使用 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 代码进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Javascript 与 Objective-c 代码进行通信?
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
