Akansha
Akansha

Reputation: 47

How to call Objective-c function from JavaScript?

I am trying to make an iphone app. In that app I am using Javascript. I want to know it is possbile to call a objective C function function from Javascript. If yes, then how can we do that? If not then is there any alternative for that?

Thanks Akansha

I have this java script code. So whenever I enter in "onPlayerStateChange" function I want to open a file and write some event in this file. But I am not able to open and write file in javascript as the location of file is not known to me. With objective-c I can open and write data in documentsDirectory, but I am not sure about javascript. So I was thinking to call a function inside "onPlayerStateChange" which is there in objective-C .m file. and that function writes in the file whenever I enter "onPlayerStateChange" function.

Can suggest anything now?

<!DOCTYPE HTML>
<html>
<body>
<div id="player"></div>
<script>
    //Load player api asynchronously.
    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var done = false;
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'JW5meKfy3fY',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    function onPlayerReady(evt) {
        evt.target.playVideo();
    }
    function onPlayerStateChange(evt) {
        if (evt.data == YT.PlayerState.PLAYING && !done) { // NEED TO ADD FILE OPERATION HERE
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }
</script>
</body>
</html>

Upvotes: 0

Views: 1719

Answers (3)

Simon McLoughlin
Simon McLoughlin

Reputation: 8465

You can create an objective c module and import it into your app and call it from JavaScript. Is this what your looking for:

http://developer.appcelerator.com/doc/mobile/iphone/module_sdk

Upvotes: 0

sElanthiraiyan
sElanthiraiyan

Reputation: 6268

You can't do it directly like in JAVA/ANDROID. Refer my answer below

iOS UIWebView Javascript - insert data -receive callbacks?

Upvotes: 1

CarlJ
CarlJ

Reputation: 9481

yes, you can create a UIWebView with the HTML/JS Context and in the

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

you can catch the request and call the obj-c method. Or you create the same solution like Appcelerator: https://stackoverflow.com/a/2471774/644629

Upvotes: 1

Related Questions