增加一個(gè)自定義插件test.js蠢笋,其中實(shí)現(xiàn)一個(gè)方法testLog,打印js傳給native的字符串
config.xml配置
config.xml是Cordova的配置文件鳞陨,Cordova在初始化的時(shí)候會(huì)加載其中的配置昨寞,自定義插件需要在其中注冊
<feature name="Test">
<param name="ios-package" value="TestPlugin" />
<param name="onload" value="true" />
</feature>
feature中是插件的映射信息,name="Test"中Test對應(yīng)的是JS中調(diào)用類名
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是唯一標(biāo)識(shí)符厦滤,對應(yīng)插件test.js中的id援岩,兩者必須相同。file是插件的相對路徑掏导。clobbers是JS中調(diào)用插件的接口
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個(gè)參數(shù)趟咆,分別為成功回調(diào)添瓷,失敗回調(diào)梅屉,類名(config.xml中的name),OC中TestPlugin類中的方法名鳞贷,參數(shù)列表坯汤。
OC中的映射類配置
新增一個(gè)繼承于CDVPlugin的類,類名TestPlugin搀愧。新增一個(gè)實(shí)例方法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調(diào)OC:Test.testLog(success, error, "123");TestPlugin類中的testLog被調(diào)用,并且傳過去的字符串“123”被打印咱筛。
OC調(diào)JS:TestPlugin類中[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];把字符串“123”當(dāng)做結(jié)果回調(diào)給JS搓幌,JS中的success被調(diào)用。