Phonegap 提供了iOS 設備的基礎特性接口來供HTML頁面調用,但是這些基礎接口不能滿足我們的一些特殊需求,所以有時候我們需要開發插件來擴展其功能。基於PhoneGap3.4框架的iOS插件開發,主要分以下幾個步驟:
1)搭建PhoneGap3.4的iOS開發環境,搭建步驟參考此文章。
2)編寫.h頭文件,示例代碼如下:
#import
@interface CDVLogin : CDVPlugin
- (void)login:(CDVInvokedUrlCommand*)command;
@end
3)編寫.m源代碼文件,示例代碼如下:
#import "CDVLogin.h"
@implementation CDVLogin
- (void)login:(CDVInvokedUrlCommand*)command{
NSString *echo = @"NIL";
//插件返回值
CDVPluginResult *pluginResult = nil;
//獲取傳遞過來的參數
NSString *param = [command.arguments objectAtIndex:0];
Boolean loginStatus = [self loginSystem:param];
if(loginStatus){
echo = @"YES";
//成功時插件的返回值
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
}else{
echo = @"NO";
//失敗時插件的返回值
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:echo];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(Boolean) loginSystem:(NSString *)para
{
return YES;
}
@end
4)在config.xml 裡注冊插件,如下:
5)js調用,如下:
var CustomPlugin = {
callNativeMethod: function (success, fail, param) {
var exec = cordova.require("cordova/exec");
return exec(success, fail,"Login","login",[param]);
}
};
function callNativePlugin( param ) {
CustomPlugin.callNativeMethod( nativePluginResultHandler, nativePluginErrorHandler, param );
}
function nativePluginResultHandler (result) {
// alert("SUCCESS: /r/n" + result);
}
function nativePluginErrorHandler (error) {
if(error == "NO"){
alert("調用失敗!");
}