Phonegap/Cordova 2.9自定义插件创建.任何工作示例

Phonegap/Cordova 2.9 Custom Plugin creation. Any working examples?

本文关键字:任何 创建 工作 插件 自定义 Cordova Phonegap      更新时间:2023-09-26

我知道github上有很多phonegap/cordova插件的例子,但我看到插件的构建方式有很多不一致。结构看起来是相同的(在大多数情况下),但几乎每种结构的代码和实现都不同。这让我不得不问几个问题。

  • 2.9文档说要使用在配置中声明插件的方法,但我收到了使用该方法的构建警告。我应该两者都用吗?

  • 在javascript中,声明/实例化插件的正确方式是什么?

  • 我是否通过窗口引用我的插件的方法。MyPlugin.myMethod还是只是window.myMMethod?

我还有更多的问题,但代码将是惊人的。

有人有一个绝对简单的例子,可以为iOS平台的cordova 2.9定制插件吗?

这是我几天前写的一个非常简单的插件,它只是为了测试构建一个基于iOS的Cordova插件。

JS:

var tester = function() {};
tester.prototype.test = function () {
    cordova.exec(
        function(result) {
            navigator.notification.alert('test plugin returned: '+result);
        },
        function() {
            navigator.notification.alert('test plugin error');
        },
        'TestPlugin',
        'test',
        ['Your test string']
    );
};
if(!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.tester) {
    window.plugins.tester = new tester();
}

调用方:

<button onclick="window.plugins.tester.test()">TEST PLUGIN</button>

TestPlugin.h:

#import <Cordova/CDV.h>
@interface TestPlugin : CDVPlugin
- (void)test:(CDVInvokedUrlCommand*)command;
@end

TestPlugin.m:

#import "TestPlugin.h"
#import <Cordova/CDV.h>
@implementation TestPlugin
- (void)test:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;
    NSString* testString = [command.arguments objectAtIndex:0];
    if (testString != nil && [testString length] > 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:testString];
    } else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

添加到/platforms/ios/{PROJECT_NAME}/Resources/config.xml:

    <plugin name="TestPlugin" value="TestPlugin" />
相关文章: