PhoneGap开发IOS,JS调用IOS方法/phoneGap插件开发——FakeMr
前沿
废话不说phoneGap是什么不多介绍,官方网站: http://phonegap.com/
之前写过phoneGap开发Android插件教程: http://my.oschina.net/jgy/blog/145385
开始代码
这个是目录结构
在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!
<feature name="MyPlugin">
<param name="ios-package" value="CDVMyPlugin" />
</feature>
最后:以上是本人测试成功后以及经验分享,欢迎吐槽交流!嘎嘎~~~~
原文链接:http://my.oschina.net/jgy/blog/175643
作者:FakeMr 郏高阳 ❤犒劳一杯咖啡❤
来源:oschina
链接:https://my.oschina.net/u/152736/blog/175643