如何从JavaScript调用Objective-C方法? [英] How can I call Objective-C methods from JavaScript?

查看:64
本文介绍了如何从JavaScript调用Objective-C方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在UIWebView上显示 SQLite 数据库内容.为此,我有一个本地HTML文件.在加载到JavaScript文件的html文件中的Body上.在Java脚本内部如何调用Objective-c方法.如何从Objective c到Java Srcipt中获取数据.

I want to display SQLite Data base content on UIWebView. For that i have a local HTML file. On Body load in html file calling JavaScript Function. Inside the Java Script how to call Objective-c method. how to get Data from Objective c to Java Srcipt.

<html>
    <head>
        <!-- a script inline --> 
        <script language="JavaScript" TYPE="text/javascript">
            <!--
            function myJsFunc() 
            { 

                //here i want to call objective-c methods.

            } 
            // -->
            </script>
        </head>
    <Body Bgcolor=#800000 onload="myJsFunc(); return true;">

        </Body>
</html>

Objective-C代码......

Objective-C code ......

- (void)viewDidLoad
{
        [super viewDidLoad];
        NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"Demo" ofType:@"html"];

    // make a file: URL out of the path
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
    [myWebView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
    [self.view addSubView:myWebView];
}
-(NSArray*)FetchingDataFromDataBase{

    // Code for retriving data from SQlite data Base, and return NSArray;
    return myArray;
}

在函数 myJSFunc ()中,如何调用-(NSArray *)FetchingDataFromDataBase.

Inside the Function myJSFunc(), how can call -(NSArray*)FetchingDataFromDataBase.

推荐答案

graver给出的博客文章解释了如何实现.

The blog post given by graver explains it how to do it.

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

如果您的类中具有上述方法,则将在加载新页面之前调用此方法.仅当此方法返回YES时,才会处理新的加载请求.我们使用这种机制来回传给Objective-C函数.

If you have the above method in your class, this method will be called before a new page is loaded. Only if this method returns YES, the new load request is processed. We use that mechanism to communicate back to the Objective-C functions.

这篇关于如何从JavaScript调用Objective-C方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆