web-dev-qa-db-fra.com

Comment appeler une fonction JavaScript dans l'objectif C

Je suis un nouveau programmeur pour Objective C. J'ai ajouté un fichier HTML à Objective C. Dans ce fichier html contient une fonction javascript simple. Je dois appeler cette fonction par le biais du code Objective C. J'ai essayé beaucoup de temps en utilisant Google. Mais je ne pouvais pas trouver un moyen réel de le faire . Le soufflet contient le fichier html:

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

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

J'ai appelé cette fonction comme ceci: est-ce correct ou incorrect? Si cela ne va pas, comment faire cela. S'il vous plaît aider. 

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()"];
22
Himesh
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()"];

Si tout ce code est appelé d'un seul endroit, cela ne fonctionnera pas, car le chargement de la page est asynchrone et que la page avec du code JavaScript n'est pas prête à ce moment-là . Essayez d'appeler cette méthode [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; dans la méthode de rappel UIWebViewDelegate –webViewDidFinishLoad:

28
Serhii Mamontov
<!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>

Ajouter un fichier html au dossier du projet . Ajoutez également votre fichier javascript au dossier du projet.

Après avoir ajouté le fichier html et ce code natif à votre 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");
}

Appelez-le dans votre méthode didLoad [self loadMyWebView];

Ici, vous pouvez ajouter n'importe quel fichier javascript au projet et l'inclure dans le fichier html. Vous pouvez appeler la fonction javascript dans la balise. (exactement comme vous appeliez les fonctions js.)

Vous pouvez passer n'importe quel paramètre à la fonction javascript et renvoyer n'importe quoi à la fonction objective.

Rappelez-vous ::: Après avoir ajouté tous les fichiers js, n'oubliez pas de les ajouter àCopy Bundle Resources

Pour éviter les avertissements ::: supprimez-les deCompile Sources

10
umakanta

On peut utiliser la structure JavaScriptCore pour exécuter du code JavaScript à partir d’Objective-C.

#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

Voici une démo:

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

8
Evgenii

NomFichier.js:

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

Copiez ce fichier dans les ressources de l'ensemble.

Maintenant #import <JavaScriptCore/JavaScriptCore.h> dans le fichier d'en-tête

 @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:@[]];

Ce bloc de code a fonctionné pour moi. Il affiche "Ceci est la fonction Javascript!" in console . J'espère que ça marche!

2
Jayprakash Dubey

Essaye ça:

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

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
0
Nag Raj