cordova外掛開發,簡單教程
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