如何在PhoneGap中编写基本的"Hello World"java脚本插件?

NS1*_*114 4 javascript html5 objective-c phonegap-plugins cordova

我已经阅读了Cordova的教程,但我不确定他们是否给了我足够的信息.

已编辑以显示更新的代码:

让我告诉你我的代码:

从config.xml:

<plugin name="someMethod" value="MyPluginClass" />
Run Code Online (Sandbox Code Playgroud)

现在为Plugin.h:

#import <Cordova/CDV.h>

@interface MyPluginClass : CDVPlugin

- (void)someMethod:(CDVInvokedUrlCommand*)command;

@end
Run Code Online (Sandbox Code Playgroud)

现在为Plugin.m:

#import "Plugin.h"

@implementation MyPluginClass

- (void)someMethod:(CDVInvokedUrlCommand *)command
{
    NSLog(@"YOU ARE READING THIS NATIVELY FROM A PLUGIN");
}

@end
Run Code Online (Sandbox Code Playgroud)

显示的第一个html页面称为"index.html"

我只想要一个空白的html页面,它只运行一个调用cordova.exec()函数的脚本.我这样做的尝试失败了.我不知道我的脚本是否有问题,或者其他地方我做错了但是这里是我的index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Cordova Device Ready Example</title>

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

        // Call onDeviceReady when Cordova is loaded.
        //
        // At this point, the document has loaded but cordova-2.3.0.js has not.
        // When Cordova is loaded and talking with the native device,
        // it will call the event `deviceready`.
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // Cordova is loaded and it is now safe to make calls Cordova methods
        //
        function onDeviceReady() {
            // Now safe to use the Cordova API
            document.addEventListener("deviceready", function() {
                                      cordova.exec(null,null,"MyPluginClass","someMethod",[]);
                                      }, false);
        }
        </script>
    </head>
    <body onload="onLoad()">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误日志:

2013-01-17 11:36:31.782 CCT [1293:907]错误:找不到插件'MyPluginClass',或者不是CDVPlugin.检查config.xml中的插件映射.

2013-01-17 11:36:31.787 CCT [1293:907] - [CDVCommandQueue executePending] [第103行] FAILED pluginJSON = ["INVALID","MyPluginClass","someMethod",[]]

wle*_*ss1 6

在设备准备事件触发之前,您无法对cordova进行任何调用.做:

 document.addEventListener("deviceready", function() {
    cordova.exec(null,null,"MyPluginClass","someMethod",[]);
 }, false);
Run Code Online (Sandbox Code Playgroud)

编辑:

对于上面列出的示例调用,您需要一个Objective-C类,如下所示:

@interface MyPluginClass : CDVPlugin

- (void)someMethod:(CDVInvokedUrlCommand*)command;

@end
Run Code Online (Sandbox Code Playgroud)

请注意与调用匹配的类的名称和方法的名称 cordova.exec

另一个编辑:

config.xml应该看起来像以下内容:

<plugin name="MyPluginClass" value="MyPluginClass" />

(这些不一定必须相同,但name应与javascript调用的第三个参数中的引用匹配,并且value应该与Objective-C类的名称匹配.

有关开发iOS插件的完整文档,请查看该指南