2024-04-20 04:17:09
开始代码
这个是目录结构
在Plugins下新建文件(在 Plugins 上右键-new file选择Objective-c class)输入名字( CDVMyPlugin ) next……
这世间你会发现在 Plugins 下面有两个文件,分别是:CDVMyPlugin.h和CDVMyPlugin.m
CDVMyPlugin.h内容:
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@interface CDVMyPlugin : CDVPlugin
@property (nonatomic, copy) NSString* callbackID;
// Instance Method
- (void) print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
CDVMyPlugin.m内容
#import "CDVMyPlugin.h"
@implementation CDVMyPlugin
@synthesize callbackID;
-(void)print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
// 这是classid,在下面的PluginResult进行数据的返回时,将会用到它
self.callbackID = [arguments pop];
// 得到Javascript端发送过来的字符串
NSString *stringObtainedFromJavascript = [arguments objectAtIndex:0];
// 创建我们要返回给js端的字符串
NSMutableString *stringToReturn = [NSMutableString stringWithString: @"我是返回的:"];
[stringToReturn appendString: stringObtainedFromJavascript];
// Create Plugin Result
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: stringToReturn];
NSLog(@ "%@",stringToReturn);
// 检查发送过来的字符串是否等于"HelloWorld",如果不等,就以PluginResult的Error形式返回
if ([stringObtainedFromJavascript isEqualToString:@"HelloWorld"] == YES){
// Call the javascript success function
[self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]];
} else{
// Call the javascript error function
[self writeJavascript: [pluginResult toErrorCallbackString:self.callbackID]];
}
}
JS封装通用调用方法
//调用IOS方法插件
var MyIOSPlugin = {
/**
* 调用IOS方法
* @param method 要调用IOS插件的方法名
* @param parameter 参数[数组]
* @param success 成功回调
* @param fail 失败回调
* @returns {*}
*/
nativeFunction: function(method, parameter, success, fail) {
return Cordova.exec(success, fail, "MyPlugin", method, parameter);
}
};
JS调用
MyIOSPlugin.nativeFunction("print",['HelloWorld'],
function(result) {
// alert("Success: \r\n"+result);
},
function(error) {
// alert("Error: \r\n"+error);
}
);
配置插件<KEY-VALUE>
<feature name="MyPlugin">
<param name="ios-package" value="CDVMyPlugin" />
</feature>
OVER!
转载