Cordova开发-2 自定义插件

一.创建插件

使用命令行创建,可以快速生成模板,节省手写编码时间。

plugman create --name MyFirstPlugin  --plugin_id  cordova-plugin-MyFirstPlugin  --plugin_version 1.0.0

--name 插件名称,建议大写,会生成类的名称

--plugin_id   将来安装删除等需要用到的

--plugin_version  版本号,根据版本情况写

二.plugin.xml说明

通过命令行方式会在plugin目录下会生成,如图

 

plugin.xml 是配置相关android ios 等平台的信息,这是一个非常重要的配置文件,在js中能否调用到插件中的本地方法就需要看这个文件中是否配置正确。

增加如下:

<js-module name="MyFirstPlugin" src="www/MyFirstPlugin.js">
<clobbers target="cordova.plugins.MyFirstPlugin" />
<!-- 前端工程师在使用的时候通过这个 clobbers 去调用www/MyFirstPlugin.js的公开方法 -->
</js-module>

<platform name="ios">
<config-file target="config.xml" parent="/*" >
<feature name="MyFirstPlugin">
<!-- 定义iOS平台下的底层实现类名为 : MyFirstPlugin -->
<param name="ios-package" value="CDVMyFirstPlugin" />
</feature>
</config-file>
<source-file src="src/ios/CDVMyFirstPlugin.m" />
<header-file src="src/ios/CDVMyFirstPlugin.h" />
</platform>

三。代码完善

1.js代码

在上面生成的代码中MyFirstPlugin.js中增加如下,

cordova.define("cordova-plugin-MyFirstPlugin.MyFirstPlugin", function(require, exports, module) {
var exec = require('cordova/exec');

exports.greetHello = function (arg0, success, error) {
exec(success, error, 'MyFirstPlugin', 'greetHello', [arg0]);
};

});

2.iOS代码

定义类CDVMyFirstPlugin,增加如下方法


- (void)greetHello:(CDVInvokedUrlCommand*)command{
NSString* name = [[command arguments] objectAtIndex:0];
NSString* msg = [NSString stringWithFormat: @"Hello, %@", name];

CDVPluginResult* result = [CDVPluginResult
resultWithStatus:CDVCommandStatus_OK
messageAsString:msg];

[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];

}

clobbers 中的target是将来js调用的,为了简化可以写成MyFirstPlugin 

cordova.plugins.MyFirstPlugin.greetHello('厉害了',sucess,error);

 

四。添加平台代码

1.添加平台代码.andorid会默认添加,ios需要手动  (这一步可以手动添加)

plugman platform add --platform_name ios    (plugman platform add --platform_name android)

2.安装package.json

plugman createpackagejson /Users/menchao/Desktop/MyFirstPlugin/MyFirstPlugin  

这个命令可能会有问题,提示pkg is not defined

改为使用npm init初始化 

3.安装插件

cordova plugins add /Users/menchao/Desktop/MyFirstPlugin/MyFirstPlugin 

4.移除插件

cordova plugin remove cordova-plugin-MyFirstPlugin

 

转载于:https://www.cnblogs.com/menchao/p/8352687.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值