1、安装Cordova环境,此处不再啰嗦
2、创建Cordova工程
cordova create testCordovaPro com.acc.testCordova testCordova
//testCordovaPro Cordova项目名
//com.acc.testCordova ID
//testCordova IOS工程名
3、进入工程目录,并添加平台
cd testCordovaPro
cordova platform add ios
添加完成以后就可以打开工程了
4、工程目录是这样的
到此,Cordova工程的ios项目已经创建完毕,并且可以直接运行查看效果
5、创建插件:在上图Plugins目录下创建插件;
注意:创建类后会报头文件#import <Cordova/Cordova.h>
找不到的问题,替换成#import <Cordova/CDVPlugin.h>
即可。
实现插件接口
@implementation TestPlugin
-(void)testWithTitle:(CDVInvokedUrlCommand *)command{
if (command.arguments.count>0) {
//customize argument
NSString* title = command.arguments[0];
TestViewController* testViewCtrl = [[TestViewController alloc]init];
[self.viewController presentViewController:testViewCtrl animated:YES completion:^{
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"callback param!"];
testViewCtrl.labTitle.text = title;
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}else{
//callback
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"have no param"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
//最后这句是传给js调用
}
}
@end
6、在config.xml文件中加入以下代码让JS能够调用我们的OC类,需要注意的是需要配置Staging下的config.xml,而不是外部的
<feature name="myTestPlugin">
<param name="ios-package" value="TestPlugin" />
</feature>
7、修改xml【staging目录下www目录下的index.xml】
<!DOCTYPE html>
<html>
<head>
<title>testPlugin</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function testPlugin() {
cordova.exec(testSuccess,testFailed,"myTestPlugin","testWithTitle",["JS传入的参数!"]);
}
function testSuccess(msg) {
alert(msg);
}
function testFailed(msg) {
alert('failed: ' + msg);
}
</script>
</head>
<body style="padding-top:100px">
<button style="font-size:17px;" onclick="testPlugin();">TestButton</button>
<br>
</body>
</html>
8、到此IOS插件开发结束,