PhoneGap插件開發示例(iOS)
重要提示:如果你同時使用phonegap(cordova)和sencha-touch,一定先引入phonegap的js文件,否則你開發的插件可能不被調用!
PhoneGap相關介紹:
PhoneGap官網
PhoneGap中國
PhoneGap插件開發的簡單步驟:
1 新建一個基於PhoneGap的工程,如果還沒有PhoneGap SDK請去官網下載安裝,我目前使用的是PhoneGap1.3.0
2 在Plugins組下新建一個PGPlugin類的子類,命名為MyPGPlugin
MyPGPlugin.h
復制代碼
- #ifdef PHONEGAP_FRAMEWORK
- #import
- #else
- #import "PGPlugin.h"
- #endif
-
- @interface MyPGPlugin : PGPlugin {
- }
-
- - (void)addStr:(NSMutableArray*)arguments withDict:(NSDictionary*)options;
-
- @end
MyPGPlugin.m
復制代碼
- #import "MyPGPlugin.h"
-
- @implementation MyPGPlugin
-
- - (void)addStr:(NSMutableArray*)arguments withDict:(NSDictionary*)options
- {
- NSLog(@"%@", arguments);
- NSString *callbackId = [arguments pop];
- NSString *result = [NSString stringWithFormat:@"%@%@", [arguments objectAtIndex:0], [arguments objectAtIndex:1]];
- PluginResult *pr = [PluginResult resultWithStatus:PGCommandStatus_OK messageAsString:result];
- [self writeJavascript:[pr toSuccessCallbackString:callbackId]];
- }
-
- @end
3 在www文件夾下新建一個js文件,這裡我也命名為MyPGPlugin
復制代碼
- /**
- * 構造方法
- */
- function MyPGPlugin() {
- };
-
- /**
- * 字符串相加
- *
- * @param str1, str2
- */
- MyPGPlugin.prototype.addStr = function(successCallback, failureCallback, str1, str2) {
- PhoneGap.exec(successCallback, failureCallback, "MyPGPlugin", "addStr", [str1, str2]);
- };
-
- /**
- * 加載MyPlugin對象
- */
- PhoneGap.addConstructor(function() {
- if(!window.plugins)
- {
- window.plugins = {};
- }
- window.plugins.myPGPlugin = new MyPGPlugin();
- });
4 修改PhoneGap.plist,展開Plugins,按”+”號新加一列.添加key MyPGPlugin和value MyPGPlugin
5 使用,在index.html中添加如下代碼:
導入js文件
復制代碼
- <script type="text/javascript" charset="utf-8" src="MyPGPlugin.js"></script>
定義js函數,添加在onDeviceReady函數定義後
復制代碼
- function addStr(){
- var str1 = "str1";
- var str2 = "str2";
- window.plugins.myPGPlugin.addStr(successCallback, failureCallback, str1, str2);
- }
- //成功時回調的方法
- function successCallback(data){
- alert("result:"+ data);
- }
- //失敗時返回的方法
- function failureCallback(data){
- alert("error:"+ data);
- }
添加一個button,測試一下
復制代碼
-
6 編譯運行。
參考鏈接:
http://www.adobe.com/devnet/html5/articles/extending-phonegap-with-native-plugins-for-ios.html
http://prostorys.blog.51cto.com/1522778/843699
http://wiki.phonegap.com/w/page/36753496/How%20to%20Create%20a%20PhoneGap%20Plugin%20for%20iOS (被牆)
隨後附上代碼免分下載地址!