cordova版本:5.1.1
cordova插件开发文档(主要是翻译,方便查询)
一.JavaScript interface
cordova.exec(function(winParam) {},
function(error) {},
"service",
"action",
["firstArgument", "secondArgument", 42, false]);
参数意义:1.成功的回调函数
2.失败的回调函数
3.native端的名称
4.native端的action名称
5.参数
-
function(winParam) {}
: A success callback function. Assuming yourexec
call completes successfully, this function executes alongwith any parameters you pass to it. -
function(error) {}
: An error callback function. If the operationdoes not complete successfully, this function executes with anoptional error parameter. -
"service"
: The service name to call on the native side. Thiscorresponds to a native class, for which more information isavailable in the native guides listed below. -
"action"
: The action name to call on the native side. Thisgenerally corresponds to the native class method. See the nativeguides listed below. -
[/* arguments */]
: An array of arguments to pass into the nativeenvironment.
window.echo = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "Echo", "echo", [str]);
};
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true.
});
二.native interface
这里主要是ios
首先,是config.xml文件中需要配置
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Echo">
<param name="ios-package" value="Echo" />
</feature>
</config-file>
</platform>
注意点:1.feature name要与exec中的service对应
2.param value要与exec中的action对应
3.param name要写成ios-package
其次,object-c的class要继承CDVPlugin
官方示例:
/********* Echo.h Cordova Plugin Header *******/
#import <Cordova/CDV.h>
@interface Echo : CDVPlugin
- (void)echo:(CDVInvokedUrlCommand*)command;
@end
/********* Echo.m Cordova Plugin Implementation *******/
#import "Echo.h"
#import <Cordova/CDV.h>
@implementation Echo
- (void)echo:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
//获取exec中传过来的参数
NSString* echo = [command.arguments objectAtIndex:0];
if (echo != nil && [echo length] > 0) {
//返回成功,messageAsString将数据返回到JavaScript。
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
} else {
//返回失败。
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
//将结果发送给<code>self.commandDelegate</code>,这样会执行JavaScript side的成功或失败方法。
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} @end