How to use Cordova plug-in in IOS

Time:2021-5-8

1、 Preparation

Plug in function: open IOS camera

1: Creating plug-ins

Plugin create — name [plugin name] – plugin_ ID [plug in ID] – plugin_ Version [plug in version number]
plugman create –name CameraDemo –plugin_id cordova-plugin-camerademo –plugin_version 1.0.0

2: Add IOS platform

plugman platform add –platform_name ios

3: Create package.json file

Package. JSON can be generated in the following two ways
1: Use the command “NPM init” to create the package.json file
2: Plugman createpackagejson [plug in path]
The ionic UI framework used by the original application cannot install plug-ins without package.json

Final plug-in directory structure

In addition to viewcontroller. H and viewcontroller. M files, other files will be automatically generated through the above steps

2、 Process

Create the files viewcontroller. H and viewcontroller. M
ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
}
@property (nonatomic,strong) UIImagePickerController *imagePicker;
- (void)getDeviceInfo;  // Get IOS device information
- (void)OpenCamera; 		// Open IOS camera
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController
- (id) init{
    Nslog (@ "= = = = = = = = = camera initialization");
    self = [super init];
    self.imagePicker = [[UIImagePickerController alloc] init];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *button =[[UIButton alloc]init];
    [button settitle: @ "I am a button" forstate: (uicontrolstatenormal)];
    [button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor blueColor] forState:(UIControlStateHighlighted)];
    [button setBackgroundColor:[UIColor yellowColor]];
    [button setFrame:CGRectMake(10, 50, 100, 30)];
    //Events
    //[button addTarget:self action:@selector(click) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button];
    
    UIButton *deviceBtn =[[UIButton alloc]init];
    [devicebtn settitle: @ "view device information" forstate: (uicontrolstatenormal)];
    [deviceBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [deviceBtn setTitleColor:[UIColor blueColor] forState:(UIControlStateHighlighted)];
    [deviceBtn setBackgroundColor:[UIColor yellowColor]];
    [deviceBtn setFrame:CGRectMake(120, 50, 200, 30)];
    [deviceBtn addTarget:self action:@selector(getDeviceInfo) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:deviceBtn];
    
    UIButton *openCameraBtn =[[UIButton alloc]init];
    [opencamerabtn settitle: @ "open camera" forstate: (uicontrolstatenormal)];
    [openCameraBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [openCameraBtn setTitleColor:[UIColor blueColor] forState:(UIControlStateHighlighted)];
    [openCameraBtn setBackgroundColor:[UIColor yellowColor]];
    [openCameraBtn setFrame:CGRectMake(330, 50, 200, 30)];
    [openCameraBtn addTarget:self action:@selector(openCamera) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:openCameraBtn];
    
    
}

- (void)getDeviceInfo{
    Nslog (@ "get device information...");
    NSString *name = [[UIDevice currentDevice] name];
    NSString *systemName = [[UIDevice currentDevice] systemName];
    NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
    NSString *model = [[UIDevice currentDevice] model];
    NSString *localizeModel = [[UIDevice currentDevice] localizedModel];
    
    UILabel *nameL = [[UILabel alloc] init];
    UILabel *systemNameL = [[UILabel alloc] init];
    UILabel *systemVersionL = [[UILabel alloc] init];
    UILabel *modelL = [[UILabel alloc] init];
    UILabel *localizeModelL = [[UILabel alloc] init];
    
    [nameL setText:name];
    [systemNameL setText:systemName];
    [systemVersionL setText:systemVersion];
    [modelL setText:model];
    [localizeModelL setText:localizeModel];
    
    [nameL setTextColor:[UIColor blueColor]];
    [systemNameL setTextColor:[UIColor blueColor]];
    [systemVersionL setTextColor:[UIColor blueColor]];
    [modelL setTextColor:[UIColor blueColor]];
    [localizeModelL setTextColor:[UIColor blueColor]];
    
    CGFloat x = 10;
    CGFloat y = 80;
    CGFloat width = 200;
    CGFloat height=20;
    
    nameL.frame = CGRectMake(x, y+20, width, height);
    systemNameL.frame = CGRectMake(x, y+40, width, height);
    systemVersionL.frame = CGRectMake(x, y+60, width, height);
    modelL.frame = CGRectMake(x, y+80, width, height);
    localizeModelL.frame = CGRectMake(x, y+100, width, height);
    
    [self.view addSubview:nameL];
    [self.view addSubview:systemNameL];
    [self.view addSubview:systemVersionL];
    [self.view addSubview:modelL];
    [self.view addSubview:localizeModelL];
}

- (void)openCamera{
    //Nslog (@ "turn on camera...");
    //UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.editing = YES;
    self.imagePicker.delegate = self;
    self.imagePicker.allowsEditing = YES;
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        Nslog (@ "select camera...");
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}
@end

These two files are actually the files that I have compiled and run under the IOS native project, and then called by camerademo. M( Actually, it’s a bit like a library.)

To put it bluntly. There is a library (viewcontroller. H and viewcontroller. M), which provides a class viewcontroller, which provides two methods

  • (void)getDeviceInfo; // Get IOS device information
  • (void)OpenCamera; // Open IOS camera

Then camerademo. M instantiates the class
CameraDemo.m

/********* CameraDemo.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "ViewController.h"

//Here, the cdvplugin class must be inherited, indicating that camerademo is a Cordova plug-in class
@interface CameraDemo : CDVPlugin {
  // Member variables go here.
}
@property (nonatomic,strong) ViewController *view;  // Declare a viewcontroller
- (void)coolMethod:(CDVInvokedUrlCommand*)command;  // Create plug-in's own method, which can be deleted
- (void)openCamera:(CDVInvokedUrlCommand*)command;
@end

@implementation CameraDemo

- (void)pluginInitialize{
    Nslog (@ "= = = = = = = = = initialize camerademo");
    [super pluginInitialize];
    //Instantiate viewcontroller 
    self.view = [[ViewController alloc] init];
}

//Create plug-in's own method, which can be deleted
- (void)coolMethod:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;
    NSString* echo = [command.arguments objectAtIndex:0];

    if (echo != nil && [echo length] > 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
    } else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)openCamera:(CDVInvokedUrlCommand*)command
{
	//The instance viewcontroller of viewcontroller is displayed
    [self.viewController presentViewController:self.view animated:YES completion:nil];
    //ViewController *view = [[ViewController alloc] init];
    //[view openCamera];
    //CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];;
    //[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

CameraDemo.js


var exec = require('cordova/exec');

exports.coolMethod = function (arg0, success, error) {
    exec(success, error, 'CameraDemo', 'coolMethod', [arg0]);
};

exports.openCamera = function (arg0, success, error) {
    exec(success, error, 'CameraDemo', 'openCamera', [arg0]);
};

Plugin.xml (this file is very, very important. JS can call OC by relying on it to check more data)


<?xml version='1.0' encoding='utf-8'?>
<plugin version="1.0.0"
    xmlns="http://apache.org/cordova/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <name>CameraDemo</name>
    <js-module name="CameraDemo" src="www/CameraDemo.js">
        <clobbers target="cordova.plugins.CameraDemo" />
    </js-module>

    <platform name="ios">
        <config-file parent="/*" target="config.xml">
            <feature name="CameraDemo">
                <param name="ios-package" value="CameraDemo" onload="true"/>
            </feature>
        </config-file>
        <source-file src="src/ios/CameraDemo.m" />
        <header-file src="src/ios/ViewController.h" />
        <source-file src="src/ios/ViewController.m" />
    </platform>
</plugin>

Package.json


{
  "name": "cordova-plugin-camerademo",
  "version": "1.0.0",
  "description": "",
  "cordova": {
    "id": "cordova-plugin-camerademo",
    "platforms": [
      "ios"
    ]
  },
  "keywords": [
    "ecosystem:cordova",
    "cordova-ios"
  ],
  "author": "",
  "license": "ISC"
}

Camerademo.js calls the native Object-C method through plugin.xml configuration

last

Cordova project calling plug in

If the call is related to the plugin. XML configuration in the plug-in, then plugin. XML is very important

// in the TS file of the project
declare let cordova:any
cordova.plugins.CameraDemo.openCamera();

The above is how to use Cordova plug-in in IOS. For more information about using Cordova in IOS, please pay attention to other related articles of developer!