2012-04-18 64 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