Cordova自定義插件配置

增加一個(gè)自定義插件test.js,其中實(shí)現(xiàn)一個(gè)方法testLog,打印js傳給native的字符串

config.xml配置

config.xml是Cordova的配置文件,Cordova在初始化的時(shí)候會(huì)加載其中的配置,自定義插件需要在其中注冊(cè)

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

feature中是插件的映射信息,name="Test"中Test對(duì)應(yīng)的是JS中調(diào)用類(lèi)名
value="TestPlugin"中TestPlugin是native端映射的OC類(lèi)名

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í)符,對(duì)應(yīng)插件test.js中的id,兩者必須相同。file是插件的相對(duì)路徑。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),類(lèi)名(config.xml中的name),OC中TestPlugin類(lèi)中的方法名,參數(shù)列表。

OC中的映射類(lèi)配置

新增一個(gè)繼承于CDVPlugin的類(lèi),類(lèi)名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類(lèi)中的testLog被調(diào)用,并且傳過(guò)去的字符串“123”被打印。

OC調(diào)JS:TestPlugin類(lèi)中[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];把字符串“123”當(dāng)做結(jié)果回調(diào)給JS,JS中的success被調(diào)用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容