上一篇文章中我们已经成功创建了一个App,在这一篇中,我们实现自定义原生插件,由js调用原生插件。在这里我们实现功能如下
一、创建插件文件 在plugins文件夹下创建插件EchoPlugin,继承自CDVPlugin,文件创建完成以后会报找不到头文件的错误,把#import <Cordova/Cordova.h>替换成#import <Cordova/CDVPlugin.h>即可
二、声明方法实现插件代码
在EchoPlugin.h文件中声明一个方法,作为原生插件对外暴露的接口供js代码调用,在.m文件中实现该方法实现iOS原生功能。
主要实现代码如下:
- (void)echo:(CDVInvokedUrlCommand*)command
{
CDVPluginResult *pluginResult = nil;
NSString *echo = [command.arguments objectAtIndex:0];
if (echo!=nil&&[echo length]>0) {
FirstViewController *testVC = [[FirstViewController alloc] init];
UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:testVC];
[self.viewController presentViewController:navVC animated:YES completion:^{
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
}else
{
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
复制代码
三、配置插件
- 修改config.xml文件 插件的功能实现以后,我们需要在项目中配置插件供js调用。首先配置config.xml文件,添加如下代码:
<platform name="ios">
<config-file parent="/*" target="config.xml">
<!-- feature的name值应该和在index.html文件中执行的exec时调用的service保持一致-->
<feature name="EchoPlugin">
<!-- value值和自定义插件的类名保持一致-->
<param name="ios-package" value="EchoPlugin" />
</feature>
</config-file>
</platform>
复制代码
注意:
要配置App最外层的config.xml文件,最外层的是全局文件,修改并编译之后会在staging下的配置文件中同样写入配置代码。如果单独修改staging文件夹下的config.xml文件,编译之后会被最全局的config.xml覆盖恢复原样。
- 修改index.html
index.html页面是Cordova创建的应用程序的入口,我们可以修改这个页面调用iOS原生功能。从js映射到插件类通过exec函数实现
exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);
复制代码
说明:
successFunction:成功的回调函数
failFunction:失败的回调函数
service:调用原生代码的服务名,和config.xml文件中的feature的name值保持一致
action:要调用的插件方法
args:要调用方法的参数,是一个数组
修改index.html页面如下:
<!DOCTYPE html>
<html>
<head>
<title>EchoPlugin</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 EchoPlugin() {
cordova.exec(testSuccess,testFailed,"EchoPlugin","echo",["我是JS传的参数!"]);
}
function testSuccess(msg) {
alert(msg);
}
function testFailed(msg) {
alert('failed: ' + msg);
}
</script>
</head>
<body style="padding-top:50px">
<button style="font-size:17px;" onclick="EchoPlugin();">Use iOS Plugin</button> <br>
</body>
</html>
复制代码
注意: 修改index.html页面也要修改最外层的全局页面
到此,第二篇文章结束。