美文网首页
Cordova自定义插件配置

Cordova自定义插件配置

作者: HiUSB | 来源:发表于2019-11-18 16:08 被阅读0次

增加一个自定义插件test.js,其中实现一个方法testLog,打印js传给native的字符串

config.xml配置

config.xml是Cordova的配置文件,Cordova在初始化的时候会加载其中的配置,自定义插件需要在其中注册

<feature name="Test">
    <param name="ios-package" value="TestPlugin" />
    <param name="onload" value="true" />
</feature>

feature中是插件的映射信息,name="Test"中Test对应的是JS中调用类名
value="TestPlugin"中TestPlugin是native端映射的OC类名

cordova_plugins.js配置

cordova.define('cordova/plugin_list', function(require, exports, module) {
  module.exports = [
  {
    "id": "cordova-plugin-test",
    "file": "plugins/test.js",
    "pluginId": "cordova-plugin-test.test",
    "clobbers": [
                 "Test"
                 ]
    }
  ];
  module.exports.metadata = {
    "cordova-plugin-test.test": "1.0.0"
  };
});

id是唯一标识符,对应插件test.js中的id,两者必须相同。file是插件的相对路径。clobbers是JS中调用插件的接口

test.js配置

cordova.define("cordova-plugin-test", function(require, exports, module) {
    var exec = require('cordova/exec');
    function Test() {};
    Test.prototype.testLog = function (suc, err, arg) {
        exec(suc, err, 'Test', 'testLog', [arg]);
    };
    var test = new Test();
    module.exports = test;
});

"cordova-plugin-test"就是cordova_plugins.js中的id,两者相同。exec()方法中有4个参数,分别为成功回调,失败回调,类名(config.xml中的name),OC中TestPlugin类中的方法名,参数列表。

OC中的映射类配置

新增一个继承于CDVPlugin的类,类名TestPlugin。新增一个实例方法testLog。

@implementation TestPlugin

- (void)testLog:(CDVInvokedUrlCommand*)command {
    NSString *arg = command.arguments.firstObject;
    NSLog(@"TestPlugin-testLog ==> %@", arg);
    CDVPluginResult *result;
    if(arg.length > 0) {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:arg];
    } else {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:arg];
    }
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

@end

index.html配置

在script中添加

function success(arg) {
    alert(arg);
}
function error() {
    alert(arg);
}
Test.testLog(success, error, "123");

JS调OC:Test.testLog(success, error, "123");TestPlugin类中的testLog被调用,并且传过去的字符串“123”被打印。

OC调JS:TestPlugin类中[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];把字符串“123”当做结果回调给JS,JS中的success被调用。

相关文章

网友评论

      本文标题:Cordova自定义插件配置

      本文链接:https://www.haomeiwen.com/subject/iedbictx.html