创建OC原生文件
1.创建子类文件HGAlertPlugin继承自CDVPlugin
2.修改HGAlertPlugin的头文件,不修改会报错
#import <Cordova/CDVPlugin.h>
3.封装oc原生方法
- 在HGAlertPlugin.h中
#import <Cordova/CDVPlugin.h>
@interface HGAlertPlugin : CDVPlugin
-(void)showObjcAlter:(CDVInvokedUrlCommand *)command;
@end
- 在HGAlertPlugin.m中
-(void)showObjcAlter:(CDVInvokedUrlCommand *)command{
if (command.arguments.count > 0) {
NSString *title = command.arguments[0];
UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//创建一个回调对象并附上String类型参数
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hey!I'm OC!"];
//通过cordova框架中的callBackID回调至JS的回调函数上
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
[alertVC addAction:action];
[self.viewController presentViewController:alertVC animated:YES completion:nil];
}
else{
//如果没有入参,则回调JS失败函数
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"没有入参alert title"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}
在config.xml中配置封装的方法
<feature name="HGAlter">
<param name="ios-package" value="HGAlertPlugin" />
<param name="onload" value="true" />
</feature>
- HGAlert方法标识
- HGAlertPlugin为oc中对应的类
在HTML资源中调用
实例代码如下:
<!DOCTYPE html>
<html>
<head>
<title>AMAlert</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">
//调用OC插件方法
function alertShow() {
//以字符串形式调用OC注入模型的实例方法
//通过cordova 将我们的模型名称,方法名,参数,成功回调的func及失败回调的func 传入
cordova.exec(alertSuccess,alertFail,"HGAlter","showObjcAlter",["Hey,I'm JS!"]);
}
//调用成功的回调函数
function alertSuccess(msg) {
alert('调用成功' + msg);
}
//调用失败的回调函数
function alertFail(msg) {
alert('调用OC失败: ' + msg);
}
</script>
</head>
<body style="padding-top:50px">
<button style="font-size:17px;" onclick="alertShow();">调用OC插件</button> <br>
</body>
</html>
cordova.exec方法参数解释
- 第一个参数:为调用oc成功的方法的回调.
- 第二个参数:为调用oc失败的方法的回调.
- 第三个参数: 在config.xml中定义的方法唯一标识.
- 第四个参数:oc中HGAlter对应类中对应的方法名.
- 第五个参数:js中给oc传的参数,是个数组,可以传多个参数.