2013-01-15 5 views
19

Ich bin ein neuer Programmierer zu Ziel C. Ich habe eine html-Datei zu Ziel C hinzugefügt. In dieser HTML-Datei enthält einfache JavaScript-Funktion. Ich muss diese Funktion durch den objektiven C-Code aufrufen. Ich habe viel Zeit mit Google versucht. Aber ich konnte keinen richtigen Weg finden, es zu tun. Bellow Enthält HTML-Datei:JavaScript ist Funktion in Ziel-C

<!DOCTYPE html> 
<html> 
    <head> 
     <script> 
      function myFunction() 
      { 
       alert("Hello World!"); 
      } 
      </script> 
    </head> 

    <body> 
     <button onclick="myFunction()">Try it</button> 
    </body> 
</html> 

ich diese Funktion wie folgt aufgerufen: Ist es richtig oder falsch ?? Wenn es falsch ist, wie geht das? Bitte helfen Sie.

NSString *path; 
NSBundle *thisBundle = [NSBundle mainBundle]; 
path = [thisBundle pathForResource:@"first" ofType:@"html"]; 
NSURL *instructionsURL = [NSURL fileURLWithPath:path]; 
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]]; 

NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"]; 
[webView stringByEvaluatingJavaScriptFromString:jsCallBack]; 

[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; 
+1

Wird die Warnung angezeigt oder nicht? – BabyPanda

+0

Wenn ich auf die Schaltfläche klicke, wird angezeigt. Aber ich möchte diese Funktion programmatisch aufrufen. – Himesh

+0

Was versuchen Sie zu erreichen? Ist Ihre Anwendung HTML5-Typ? Warum nicht natives UIKit verwenden? – pbibergal

Antwort

25
NSString *path; 
NSBundle *thisBundle = [NSBundle mainBundle]; 
path = [thisBundle pathForResource:@"first" ofType:@"html"]; 
NSURL *instructionsURL = [NSURL fileURLWithPath:path]; 
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]]; 

NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"]; 
[webView stringByEvaluatingJavaScriptFromString:jsCallBack]; 

[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; 

Wenn das alles Code aus einem Ort namens, als es nicht funktionieren wird, weil Seite zu laden asynchron ist und die Seite mit JavaScript-Code ist in diesem Moment nicht bereit. Versuchen Sie, diese Methoden [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; in UIWebViewDelegate Callback-Methode aufrufen –webViewDidFinishLoad:

+0

Wirklich danke für Ihre Antwort. Es funktioniert zu 100%. Nochmals vielen Dank. – Himesh

+0

Die Antwort ist sehr richtig. Ich gebe zusätzliche Funktionalität zu diesem Danke !! – umakanta

+0

Bitte lassen Sie uns wissen, wie mit iOS 8 wkwebview zu tun? –

9
<!DOCTYPE html> 
<html> 
<head> 

    <script type="text/javascript" charset="utf-8" src="your.js"></script> 
    <script type="text/javascript" charset="utf-8" src="andYourJsfileName.js"></script> 

    <script> 
     function myFunction('yourParameter') 
     { 
      // do your javascript operation 

      //alert("my Hello World!"); 
      return value; 
     } 

    </script> 
</head> 

<body> 
    <!--button onclick="myFunction()">Try it</button--> 
</body> 

eine HTML-Datei hinzufügen Ordner zu projizieren. Fügen Sie Ihre Javascript-Datei auch zum Projektordner hinzu.

Nach dem Hinzufügen der HTML-Datei und diesen nativen Code in Ihrem viewController.m

-(void)loadMyWebView { 
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)]; 
    NSString *path; 
    NSBundle *thisBundle = [NSBundle mainBundle]; 
    path = [thisBundle pathForResource:@"first" ofType:@"html"]; 
    NSURL *instructionsURL = [NSURL fileURLWithPath:path]; 

    NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 

    webView.delegate=self; 

    [webView loadHTMLString:htmlString baseURL:instructionsURL]; 
    // [self.view addSubview:webView]; (if you want to access the javascript function and don't want to add webview, you can skip that also.) 
} 


- (void)webViewDidFinishLoad:(UIWebView*)theWebView { 
    NSString* returnValue =[theWebView stringByEvaluatingJavaScriptFromString:@"myFunction('pass your parameter')"]; 
    NSLog(@"returnValue = %@ ",returnValue); 
} 

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ 

    NSLog(@" didFailLoadWithError"); 
} 

Rufen Sie diese in Ihrer didLoad Methode [self loadMyWebView];

Hier können Sie beliebige Javascript-Datei in das Projekt ein und schließen es an die HTML-Datei. Sie können JavaScript-Funktion innerhalb des Tags aufrufen. (genau so, wie Sie js-Funktionen aufgerufen haben.)

Sie können einen beliebigen Parameter an die JavaScript-Funktion übergeben und alles an die Zielfunktion zurückgeben.

Erinnern ::: Nachdem Sie alle JS-Datei vergessen Sie nicht, sie zu Warnung Copy Bundle Ressourcen

Um zu vermeiden, hinzufügen ::: sie entfernen Compile Sources

+0

aufrufen ObjectiveC aus Javascript :: http://blog.techno-barje.fr/post/2010/10/06/UIWebView-secrets- part3-Wie-richtig-nennen-ObjectiveC-from-Javascript/ – umakanta

8

Man kann JavaScriptCore-Framework verwenden, um JavaScript-Code von Objective-C auszuführen. Hier

#import <JavaScriptCore/JavaScriptCore.h> 

... 

JSContext *context = [[JSContext alloc] init]; 
[context evaluateScript: @"function greet(name){ return 'Hello, ' + name; }"]; 
JSValue *function = context[@"greet"]; 
JSValue* result = [function callWithArguments:@[@"World"]]; 
[result toString]; // -> Hello, World 

ist eine Demo:

https://github.com/evgenyneu/ios-javascriptcore-demo

+0

Einschließlich der Import hat mir geholfen, danke Mann. – antihero989

+0

@Evengii Wie in https://www.bignerdranch.com/blog/javascriptcore-example/ erwähnt, könnte dies zur Ablehnung unserer App von Apple führen. – ViruMax

0

Try this:

NSString *jsCallBack = [NSString stringWithFormat:@"setPhoto('%@')",profileImgPath]; 

[webView stringByEvaluatingJavaScriptFromString:jsCallBack]; 
1

FileName.js:

function greet() { 
    hello(“This is Javascript function!”); 
} 

Kopieren Sie diese Datei in Bundle-Ressourcen.

Jetzt #import <JavaScriptCore/JavaScriptCore.h> in Header-Datei

@property (nonatomic,strong) JSContext *context; // Declare this in header file 

     // This code block goes into main file 
     NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"js"]; 
     NSString *scriptString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil]; 

     self.context = [[JSContext alloc] init]; 
     [self.context evaluateScript:scriptString]; 

     self.context[@"hello"] = ^(NSString text) { 
      NSLog(@"JS : %@",text); 
     } 

     JSValue *function = self.context[@"greet"]; 
     [function callWithArguments:@[]]; 

Dieser Codeblock für mich gearbeitet. Es zeigt "Dies ist Javascript-Funktion!" in der Konsole. Hoffe, das funktioniert!

Verwandte Themen