cordova 插件 (最簡單蠢箩,步驟最少的實現(xiàn))
1链蕊、 JS調(diào)用AlfreldPlugin 為暴露出來的名稱,myMethod為方法名谬泌。
// index.js
Cordova.exec(successFunction, failFunction, "AlfreldPlugin", "myMethod", ["function"]);
2滔韵、 config.xml,配置AlfreldPlugin 到 TestPlugin的映射掌实,
<feature name="AlfreldPlugin">
<param name="ios-package" value="TestPlugin" />
<param name="onload" value="true" />
</feature>
3陪蜻、原生實現(xiàn)
//TestPlugin.h
@interface TestPlugin : CDVPlugin
- (void)myMethod:(CDVInvokedUrlCommand*)command;
@end
//TestPlugin.m
@implementation TestPlugin
-(void) pluginInitialize {
return;
}
- (void)myMethod:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* myarg = [command.arguments objectAtIndex:0];//獲取第一個參數(shù)
if (myarg != nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"return Data :) "];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Arg was null"];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
cordova 插件 (標(biāo)準(zhǔn)實現(xiàn))
1、barcodescanner.js 中實現(xiàn)調(diào)用贱鼻,注意BarcodeScanner為config.xml中的BarcodeScanner
cordova.define("phonegap-plugin-barcodescanner.BarcodeScanner", function(require, exports, module) {
var exec = cordova.require("cordova/exec");
var scanInProgress = false;
function BarcodeScanner() {//......};
//......
BarcodeScanner.prototype.scan = function (successCallback, errorCallback, config) {
exec(
function(result) {
scanInProgress = false;
successCallback(result);
},
function(error) {
scanInProgress = false;
errorCallback(error);
},
'BarcodeScanner',
'scan',
config
);
};
//......
var barcodeScanner = new BarcodeScanner();
module.exports = barcodeScanner;
});
2宴卖、cordova_plugin.js實現(xiàn)對插件的配置滋将,注意:該配置中id為1中define的內(nèi)容,pluginId為module.exports.metadata的內(nèi)容症昏,file指向barcodescaner.js,clobbers為調(diào)用插件時的引用随闽。
{
"id": "phonegap-plugin-barcodescanner.BarcodeScanner",
"file": "plugins/phonegap-plugin-barcodescanner/www/barcodescanner.js",
"pluginId": "phonegap-plugin-barcodescanner",
"clobbers": [
"cordova.plugins.barcodeScanner"
]
},
//...
module.exports.metadata =
{
"phonegap-plugin-barcodescanner": "6.0.6",
};
3、config.xml肝谭,CDVBarcodeScaner為實際的類名
<feature name="BarcodeScanner">
<param name="ios-package" value="CDVBarcodeScanner" />
</feature>
4掘宪、原生實現(xiàn)
5、js調(diào)用分苇,注意cordova.plugins.barcodeScanner跟步驟2中的clobbers一致添诉。
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
插件開發(fā)時的注意事項
1、當(dāng)下面參數(shù)設(shè)置為 YES 可以設(shè)置多次跟js進行交互
- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback;
2医寿、CDVPlugin中可以通過變量viewController獲取當(dāng)前頁面所在的viewController
[self.viewController presentViewController:_readerViewController animated:YES completion:nil];