標籤:style blog http tar com get
Phonegap 提供了iOS 裝置的基礎特性介面來供HTML頁面調用,但是這些基礎介面不能滿足我們的一些特殊需求,所以有時候我們需要開發外掛程式來擴充其功能。基於PhoneGap3.4架構的iOS外掛程式開發,主要分以下幾個步驟:
1)搭建PhoneGap3.4的iOS開發環境,搭建步驟參考此文章。
2)編寫.h標頭檔,範例程式碼如下:
#import <Cordova/CDVPlugin.h> @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 裡註冊外掛程式,如下:
<feature name="Login"> <param name="ios-package" value="CDVLogin"/> </feature> |
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("調用失敗!"); }
|