参考地址:http://docs.phonegap.com/en/2.9.0/guide_plugin-development_ios_index.md.html#Developing%20a%20Plugin%20on%20iOS
1、新建插件文件:
2、Native端
Interactive.h
//
// Interactive.h
// middleware
//
// Created by bo on 13-7-1.
//
//
#import <Cordova/CDV.h>
//有些老版本(貌似是phonegap 1.5.0之前)的引用是 #import <PhoneGap/PGPlugin.h>
@interface Interactive : CDVPlugin
//貌似是phonegap 1.5.0之前需要继承 PGPlugin
/*旧的插件方法*/
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
/*新的插件方法 ponegap 2.1.0版本开始*/
- (void) myPluginMethod:(CDVInvokedUrlCommand*) command;
@end
Interactive.m
//
// Interactive.m
// middleware
//
// Created by bo on 13-7-1.
//
//
#import "Interactive.h"
@implementation Interactive
- (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];
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
3、plugins的配置
phonegap 2.1.0之前的配置方法:
找到PhoneGap.list (phonegap 1.5.0之前版本)或cordova.list(phonegap 1.5.0-2.1.0之间版本的配置),添加包名和js端需要引用的name名,分别为:com.ian.Interactive和Interactive,如图:
找到config.xml,在<plugins></plugins>内添加
<feature name="Interactive">
<param name="ios-package" value="Interactive" />
</feature>
<feature name="Interactive"> 这个“Interactive”是给js端引用时的一个name值
<param name="ios-package" value="Interactive">中,name值为"ios-package"是不变的,
value="Interactive" 这里的value值取的是继承CDVPlugin的类名,即Interactive.h中@interface Interactive : CDVPlugin 的 Interactive, 而不是像phonegap2.1.0之前版本一样取的是包名+类名
如图:
4、js端
//exec(<successFunction>,<failFunction>,<service(在config中配置的name)>,<action>,[<args>]);
Cordova.exec( function(){
console.log("success!!!!!");
}, function(){
console.log("fail");
}, "Interactive", "myPluginMethod", ['success'])
到这里IOS端,js与native通过phonegap的插件进行相互调用配置结束。
下面是phonegap 2.8.1版本的 phonegap插件进行js与native的相互调用 范例
http://pan.baidu.com/share/link?shareid=2982847956&uk=1964506139