参考 :http://moduscreate.com/building-a-custom-phonegap-plugin-for-ios/
新项目中要用到Phonegap,发现网上的创建Plugin的帖子都是些旧的,看的一头雾水,为了方便大家不在走弯路,总结了下。
创建一个新的插件大概有3个步骤:
1、在Xcode工程的Plugins文件夹下创建一个类并且继承于CDVPlugin。
2.plugins的配置
3.写JS文件
4.在Index.html文件中引入调用
具体如下:
1。新创建类文件,如下图:
MyPlugin.h文件
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@interface MyPlugin : CDVPlugin
/*旧的插件方法*/
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
/*新的插件2.9.0方法 */
- (void) myPluginMethod:(CDVInvokedUrlCommand*) command;
@end
MyPlugin.m文件
#import "MyPlugin.h"
@implementation MyPlugin
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
//get the callback id
NSString *callbackId = [arguments pop];
NSLog(@"Hello, this is a native function called from PhoneGap/Cordova!");
NSString *resultType = [arguments objectAtIndex:0];
CDVPluginResult *result;
if ( [resultType isEqualToString:@"success"] ) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"];
[self writeJavascript:[result toSuccessCallbackString:callbackId]];
}
else {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString: @"Error :("];
[self writeJavascript:[result toErrorCallbackString:callbackId]];
}
}
- (void) myPluginMethod:(CDVInvokedUrlCommand*) command{
CDVPluginResult* pluginResult = nil;
NSString* echo = [command.arguments objectAtIndex:0];//获取冲js文件传过来的
NSLog(@"js文件传过来的:%@", echo);
if (echo != nil && [echo length] > 0) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
2.plugins的配置
在之前的早版本都是在Phonegap.plist文件中,加入相对应的key 和value进行操作
新方法是在config.xml中<plugins></plugins>添加:如下图:
3.写JS文件
Cordova.exec( function(){
navigator.notification.alert("success");
}, function(){
navigator.notification.alert("fail");
}, "Myplugin", "Myplugin", ['success']);
如图:
4.在Index.html中引用
<scripttype="text/javascript"src="js/index.js"></script>。也可以设置成自定义的JS文件,现在是在创建工程时自带的JS文件里进行的设置,所在Index.html文件里默认是有这个一项的,这里有个要注意的地方:<script type="text/javascript"src="js/index.js"></script>一定在写在<scripttype="text/javascript"src="cordova.js"></script>的后面。
在此就完成了所有的操作,Demo就不上传了,照片步骤基本上就可以实现了。
2013年12月16日,由于是上周做的笔记,今天翻看时发现了一个问题在此更正下,上图中,Cordova.exec的几个参数中有错误,应该是
Cordova.exec( function(){
navigator.notification.alert("success");
}, function(){
navigator.notification.alert("fail");
}, "MyPlugin","myPluginMethod", ['success']);
}
,重新对这个做下解释:在Cordova.exec的几个参数中,success, fail,都是回调函数, 当成功,失败时,分别调用这两个, 第三个"Myplugin"指js的类名, "myPluginMethod"指对应的本地代码的方法(Plugins目录下新创建的类方法),types就是用户的输入值。
还是把代码放出来吧,地址:http://download.csdn.net/detail/quanqinayng/6721031。有问题还请大家提出来。