2012-04-18 113 views
3

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

<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代码 ......

- (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.

+2

看看这篇博文:http://blog.techno-barje.fr/post/2010/10/06/UIWebView-secrets-part3-How-to-properly-call-ObjectiveC-from-Javascript/ – graver 2012-04-18 09:45:59

+1

'脚本'元素上的'language'属性已被弃用了十多年,现在可以不再使用了。 'type'属性应该是小写,但坦率地说,你[不需要](http://www.w3.org/TR/html5/the-script-element.html#attr-script-type ),除非你包含一个脚本*而不是用JavaScript编写(这是HTML5规范只是编纂现有惯例的一个领域,而不是指定新的东西)。 – 2012-04-18 09:46:53

回答

1

通过刻刀给出的博客文章解释它如何做到这一点。

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

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

+2

我可以从外部Java脚本调用Objective c函数吗? – Musthafa 2012-04-25 11:02:46