webview 有什么办法可以与原生 iOS 应用程序进行通信吗?
我有一个包含网络视图的 iPad 应用程序。 Web 视图的页面上有一个按钮,单击该按钮时,需要以某种方式告诉本机应用程序关闭 Web 视图。有什么办法可以做到这一点吗?即 webview 中的 javascript 将消息传递到本机应用程序的一种方式,反之亦然?
谢谢!
I have an iPad app that contains a webview. The webview's page has a button on it that, when clicked, needs to somehow tell the native app to close the webview. Is there any way to do this? i.e. a way for the javascript in the webview to pass messages to the native app, and vice-versa?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当
NSString
实例字段更改时,可能会触发NSNotification
。使用此处的帖子来帮助了解如何沟通JavaScript 和 Objective-C 之间。然后,这只是通知和字符串逻辑的问题:
JavaScript 到 Objective-C 的步骤:
不确定您想要从 Objective-C 传递回 Web 视图的内容,但上面的帖子应该会有所帮助。
Maybe have an
NSNotification
fire when anNSString
instance field is changed. Use the post here to help understand how to communicate between JavaScript and Objective-C.Then, it is just a matter of notification and string logic:
Steps for JavaScript to Objective-C:
Not sure what you want to pass back to the Web view from Objective-C, but the above post should help.
您可以附加任何用于
从您的 web 视图中检测 javascript 的操作!
这是文档: http://developer .apple.com/library/ios/#documentation/uikit/reference/UIWebView_Class/Reference/Reference.html
You can attach any action using
that detects the javascript from your webview!
Here is the doc: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebView_Class/Reference/Reference.html
我认为最好的方法是使用伪图像代替。
JS 将插入一个新图像,例如: http://example.com/callnative_1354524562763。 gif?p1=v1&p2=v2
并且您的 Web 视图将覆盖
NSURLCache
以检索 1x1 透明图像并解析 Web 内容中的参数。请注意,
NSURLCache
仅缓存一次,因此请为每次调用生成新的时间戳。这种方式适用于我的项目,并立即调用本机 iOS 应用程序。
I think the best way is using pseudo image instead.
JS will insert a new image such as: http://example.com/callnative_1354524562763.gif?p1=v1&p2=v2
And your webview will override
NSURLCache
to retrieve 1x1 transparent image and parse parameters from you web content.Note that
NSURLCache
only cache only one times, so please generate new timestamp for each calls.This way is work for my project and call native iOS app immediately.
您可以考虑使用
-webView:shouldStartLoadWithRequest:navigationType:
。创建一个虚拟链接,您可以识别该链接并关闭 Web 视图。至于反过来,@Paska 的回答听起来很合适。You can consider using
-webView:shouldStartLoadWithRequest:navigationType:
. Create a dummy link which you can identify and close the web view. As for the other way round, @Paska's answer sounds appropriate.