从objective-c调用javascript函数的语法

Syntax to call javascript function from objective-c

本文关键字:语法 函数 javascript objective-c 调用      更新时间:2023-09-26

我正在用phonegap/cordova 2.1.0框架制作IOS应用程序。我想调用一个javascript函数驻留在index.html从objective-c。所以,首先我正在加载index.html,然后尝试调用javascript函数。我的代码如下:

 NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www"];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    NSString *myFile = [path stringByAppendingPathComponent:@"index.html"];
//NSLog(@"base url= %@",myFile);
NSData *myFileData = [[NSData alloc] initWithContentsOfFile:myFile];
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
[theWebView loadHTMLString:myFileHtml baseURL:baseURL];
// to call javascript function 
[theWebView stringByEvaluatingJavaScriptFromString:@"onDeviceReady()"];

最后第二行加载index.html,最后一行调用其中的函数。但是,不知何故,上面的代码不工作。我是不是在语法方面有问题。

另外,由于index.html之前已经被加载,所以我如何指定文件名(即。Index.html),其中的功能存在没有再次加载它?谢谢。

Javascript函数如下:

function onDeviceReady(callback) {
                var item = window.localStorage.getItem("key");
                var message = "deviceready localStorage.getItem('key')="+item+" localStorage.length="+window.localStorage.length;
                if( item == null){
                    item = "";
                }
                item = item + "value";
                window.localStorage.setItem("key", item);
                var value = window.localStorage.getItem("key");
                if ( deviceType == 'android' && gAppControl.loadScript == false ){
                    loadScript('iscroll.js');
                    gAppControl.loadScript = true;
                    document.addEventListener("backButton", backPressed, false);
                }
                var db = window.openDatabase(dbName, "1.0", gAppConfig.dbMessage, 200000);
                db.transaction(queryDB, errorCB , callback);
                // return
                return;
            }
onDeviceReady()

这是phonegap API,如果设备没有准备好,你将无法调用任何phonegap插件,那么onDeviceReady()函数中的细节是什么?涉及到phonegap插件吗?

代码似乎没有问题,这是我的代码,有一个桥与Objective-C和HTML-Javascript通信,