本文介绍了从某些网页上托管的JavaScript调用Objective-C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IOS应用程序,其中包含一个Web浏览器。

I have an IOS application which has a web browser in it.

当显示此Web浏览器时,它会导航到Internet上的页面,例如。

When this web browser is displayed, it navigates to a page on Internet, say http://myexample.com/myiosapp.

是否有可能在此网站上放置一个javascript代码,当下载到手机时,它与本机应用程序进行通信?它可以调用Objective-C方法,还是写一些东西到这个应用程序的存储空间?

Is it possible to place a javascript code on this web site, which, when downloaded to phone, communicates with the native application? Can it call an Objective-C method, or write something to storage space of this application?

Ex。
myexample.com/myios app上托管的代码:

Ex.Code hosted on myexample.com/myios app:

function saveSomeString() {
    xcode.Save("somestring");
}

应该调用一个名为Save的Objective-C函数,它将传入的字符串参数保存到本地存储。

should call an Objective-C function named Save, which saves incoming string parameter to local storage.

推荐答案

是的,你可以,但它有点hacky。

Yes, you can, but it is a bit hacky.

在Objective-C方面:

基本上,在UIWebView中,您将使用方法shouldStartLoadWithRequest(来自UIWebViewDelegate)在URL请求开始之前调用:

Basically, in the UIWebView, you will use method shouldStartLoadWithRequest (from the UIWebViewDelegate) which is called before a URL request starts:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

在Javascript方面:

您的javascript代码将导航到您将根据上述方法过滤的假网址。类似于:

Your javascript code will navigate to a 'fake' URL that you will filter on the method above. Something like:

window.location = "js2objc://save:param";

回到Objective-C方面:

在我前面提到的方法中,你找到关键字js2objc(或你选择的任何一个),然后提取信息并采取任何适当的行动:

Inside the method I mentioned earlier, you look for the keyword js2objc (or whichever you choose) and then extract the info and take any appropriate action:

if([[url scheme] isEqualToString:@"js2objc"]){
    // extract the parameters and save them, o do whatever action you need
    return NO;  // so the UIWebView doesn't actually follow the url
}

这篇关于从某些网页上托管的JavaScript调用Objective-C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:13