Cordova 自定义插件

创建OC原生文件

1.创建子类文件HGAlertPlugin继承自CDVPlugin

2.修改HGAlertPlugin的头文件,不修改会报错

#import 

3.封装oc原生方法

  • 在HGAlertPlugin.h中
#import 

@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中配置封装的方法

 
        
        
    
  • HGAlert方法标识
  • HGAlertPlugin为oc中对应的类

在HTML资源中调用

实例代码如下:



    
        AMAlert
        
            
            
            
    
    
         

cordova.exec方法参数解释

  • 第一个参数:为调用oc成功的方法的回调.
  • 第二个参数:为调用oc失败的方法的回调.
  • 第三个参数: 在config.xml中定义的方法唯一标识.
  • 第四个参数:oc中HGAlter对应类中对应的方法名.
  • 第五个参数:js中给oc传的参数,是个数组,可以传多个参数.

你可能感兴趣的:(Cordova 自定义插件)