问题描述
在原生 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 代码进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)