Custom plugin create in ionic 7 with Capacitor in Mac

 

How to Create a Custom Capacitor Plugin and Add it to an Ionic 7 Project

In this tutorial, we will go through the steps required to set up an Ionic project with Capacitor, configure it for iOS, and ensure your project is properly synced.

1. Set Up Your Environment

Install Node.js and Required Tools

  1. Use Node.js version 18.20.5:

    nvm use v18.20.5
    
  2. Install the Ionic CLI:

    npm install -g @ionic/cli@7.2.0
    

2. Create an Ionic 7 App

  1. Create a new Ionic app:

    ionic start AppName --type=angular
    
  2. Serve the app in your browser:

    ionic serve
  3. To add Capacitor functionality and the Android/iOS platform:
  4. Add Android platform (optional):

    ionic cordova platform add android
  5. Add iOS platform (optional):

    ionic cordova platform add ios
  6. Install Capacitor:

    npm install @capacitor/core @capacitor/cli
    
  7. Initialize Capacitor:

    npx cap init AppName com.example.app

[error] Cannot run init for a project using a non-JSON configuration file.

        Delete capacitor.config.ts and try again.

This will generate a capacitor.config.ts file, which can be later updated to a JSON configuration file.

Step 4: Sync the Project

Once you have initialized Capacitor and added the iOS platform, sync the project:

  1. Run the Sync Command

    npx cap sync

    This will sync your project with the Capacitor configurations and platform-specific code.

Step 5: Update the Capacitor Configuration File

By default, Capacitor generates a TypeScript configuration file. If you prefer JSON, you can manually update it.

  1. Update capacitor.config.ts to capacitor.config.json

    Replace the capacitor.config.ts file with the following JSON configuration:

    json
    {
      "appId": "com.example.app",
    "appName": "Sample App", "bundledWebRuntime": false, "npmClient": "npm", "webDir": "www"
    }

    This configuration defines your app ID, name, and other settings.

Step 6: Check and Update Capacitor Version

It is always a good idea to check the current version of Capacitor. You can verify the version with:

npx cap --version

You may get an output like:

4.8.2

If you need to update Capacitor to the latest version, you can do so with:

  1. Update Capacitor CLI to the Latest Version

    npm install @capacitor/cli@latest
  2. Check the Updated Version

    Once the update is complete, check the version again:

    npx cap --version

    This should output:

    6.2.0

4. Build and Sync the Project

  1. Build the Ionic app to generate the www folder:

    ionic build
    
  2. Sync the Capacitor project:

    npx cap sync
    

5. Run the App

  • For Android:

    ionic cap run android --livereload
    
  • For iOS:

    ionic cap run ios --livereload
    

6. Create a Custom Capacitor Plugin

6.1 Set Up the Plugin Directory

  1. Navigate to your Ionic project directory:

    cd /path/to/your/ionic/project
    
  2. Create a plugins folder:

    mkdir plugins
    cd plugins
    
  3. Initialize a new Capacitor plugin:

    npm init @capacitor/plugin@latest
    

6.2 Plugin Setup Prompts

  • NPM Package Name: fss-sdk-cap-plugin
  • Plugin Directory: fss-sdk-cap-plugin
  • Package ID: com.fss.sdk
  • Class Name: FssSdkCapacitorPlugin
  • Repository URL: http://github.com/manikandank
  • Author: Manikandan K
  • License: MIT
  • Description: Fss SDK with Capacitor using Ionic 7

7. Build Your Plugin

Compile the plugin code:

npm run build

8. Integrate the Plugin with Your Ionic Project

  1. Link the plugin to your Ionic app:

    npm install ./plugins/fss-sdk-cap-plugin
    
  2. Update your app's package.json to include the plugin:

    "dependencies": {
      "fss-sdk-cap-plugin": "file:plugins/fss-sdk-cap-plugin"
    }
    
  3. Sync the Capacitor project:

    npx cap sync
    

9. Use the Plugin in Your Ionic App

  1. Import the plugin in your component or service:

    import { FssSdkCapacitorPlugin } from 'fss-sdk-cap-plugin';
    
    const plugin = new FssSdkCapacitorPlugin();
or - You can invoke the plugin from your component through the below code.


initializeApp() {
/* To make sure we provide the fastest app loading experience
for our users, hide the splash screen automatically
when the app is ready to be used:

https://capacitor.ionicframework.com/docs/apis/splash-screen#hiding-the-splash-screen
*/
// Usage without instantiating, assuming it's a singleton API
SdkCapacitorPlugin.echo({ value: 'Hello, Plugin!' })
.then(result => console.log(result.value))
.catch(error => console.error(error));
SplashScreen.hide();
}
  1. Call plugin methods:

    plugin.echo({ value: 'Hello, Plugin!' })
      .then(result => console.log(result.value));
    

10. Test Your Plugin

  • Run the App for Testing:
    • For web:

      ionic serve
      
    • For Android:

      npx cap open android
      
    • For iOS:

      npx cap open ios
      


To add a screen in a Capacitor plugin, you typically need to integrate native code (iOS or Android) that will display a screen (e.g., a native UI such as a new activity in Android or a view controller in iOS). Here's a general process on how to add a screen (UI) in your custom Capacitor plugin:

Define Methods to Show the Screen

You'll need to define methods in your plugin's code that will trigger the native screen to be shown. You can add platform-specific code for both iOS and Android.

Example: Show Screen on Android

For Android, you need to define an Activity that will be launched.

  1. Create a new Activity in your Android project (located in the plugin's android directory).

    • Navigate to the src/main/java/ directory in your plugin's Android folder.
    • Create a new activity, for example, ScreenActivity.java:
package com.fss.sdk;

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public class ScreenActivity extends BridgeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add your screen-specific logic here (e.g., show a UI, a layout, etc.)
// Set the activity layout
setContentView(R.layout.activity_screen);

// Find the button in the layout
Button buttonClose = findViewById(R.id.buttonClose);

// Add a click listener to close the activity
buttonClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish(); // Close the activity
}
});
}
}

Create a Layout File

  1. Navigate to your plugin's android directory:

    /path/to/your/plugin/android/src/main/res/
  2. Inside the res folder, create a layout folder if it doesn’t exist:

    /src/main/res/layout/
  3. Add an XML layout file, for example, activity_screen.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:gravity="center">

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Capacitor Plugin Screen!"
    android:textSize="18sp"
    android:textStyle="bold"
    android:layout_gravity="center_horizontal" />

    <Button
    android:id="@+id/buttonClose"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Close"
    android:layout_marginTop="20dp"
    android:layout_gravity="center_horizontal" />

    </LinearLayout>

3. Update Your AndroidManifest.xml

Make sure your ScreenActivity is declared in the AndroidManifest.xml file of your plugin.

  1. Open AndroidManifest.xml located in:

    /src/main/AndroidManifest.xml
  2. Add the activity entry in ionic app android directory:


<activity android:name="com.fss.sdk.ScreenActivity"
android:exported="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
tools:ignore="WrongManifestParent" />
  1. Update the Plugin Code to Launch the Activity:

In your plugin's Android code (typically in MainActivity.java or a custom handler file), you can create a method to launch the new activity:

Call the Screen from the Plugin

Ensure your plugin is correctly set up to launch the new activity.

Update your plugin class (e.g., FssSdkCapacitorPlugin.java) to call the ScreenActivity:

package com.fss.sdk;

import android.content.Intent;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

@CapacitorPlugin(name = "FssSdkCapacitorPlugin")
public class FssSdkCapacitorPluginPlugin extends Plugin {

private FssSdkCapacitorPlugin implementation = new FssSdkCapacitorPlugin();

@PluginMethod
public void echo(PluginCall call) {
String value = call.getString("value");

JSObject ret = new JSObject();
ret.put("value", implementation.echo(value));
call.resolve(ret);
}

    @PluginMethod
public void openSdkScreen(PluginCall call) {
        Intent intent = new Intent(getContext(), ScreenActivity.class);
getContext().startActivity(intent);
}
}

You will call openScreen() from your Ionic/Capacitor app to trigger the new screen.

Example: Show Screen on iOS

For iOS, you need to add a UIViewController to your plugin's iOS code.

  1. Create a new ViewController in your plugin's ios directory.

    • Go to ios/Plugin/ and add a new Swift file, e.g., ScreenViewController.swift:
import Foundation
import Capacitor

/**
* Please read the Capacitor iOS Plugin Development Guide
* here: https://capacitorjs.com/docs/plugins/ios
*/
@objc(FssSdkCapacitorPluginPlugin)
public class FssSdkCapacitorPluginPlugin: CAPPlugin, CAPBridgedPlugin {
public let identifier = "FssSdkCapacitorPluginPlugin"
public let jsName = "FssSdkCapacitorPlugin"
public let pluginMethods: [CAPPluginMethod] = [
CAPPluginMethod(name: "echo", returnType: CAPPluginReturnPromise)
]
private let implementation = FssSdkCapacitorPlugin()

@objc func echo(_ call: CAPPluginCall) {
let value = call.getString("value") ?? ""
call.resolve([
"value": implementation.echo(value)
])
}
@objc func openSdkScreen(_ call: CAPPluginCall) {
DispatchQueue.main.async {
let viewController = ScreenViewController()
self.bridge?.viewController?.present(viewController, animated: true, completion: nil)
}
}
}



Create the ScreenViewController class (e.g., ScreenViewController.swift):

import UIKit

class ScreenViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Add UI elements, such as buttons or labels, for your screen
let label = UILabel()
label.text = "Hello from the custom screen!"
label.frame = CGRect(x: 20, y: 50, width: 300, height: 50)
view.addSubview(label)
}
}

Define Plugin Methods for Your App

Now that you've set up native code to show the screen on both Android and iOS, you'll want to expose this functionality to your Ionic app.

In your plugin's src/web/plugin.ts file, expose the method that will call the native code.


import { WebPlugin } from '@capacitor/core';

import type { FssSdkCapacitorPluginPlugin } from './definitions';

export class FssSdkCapacitorPluginWeb extends WebPlugin implements FssSdkCapacitorPluginPlugin {
async echo(options: { value: string }): Promise<{ value: string }> {
console.log('ECHO', options);
return options;
}
async openSdkScreen(): Promise<void> {
console.log('Opening screen (Web not supported)');
}
}

definition.ts

export interface FssSdkCapacitorPluginPlugin {
echo(options: { value: string }): Promise<{ value: string }>;
openSdkScreen(): any;
}


In your native code, update the FssSdkCapacitorPlugin.java (Android) or FssSdkCapacitorPlugin.swift (iOS) to implement the native openScreen() functionality.


4. Use the Plugin in Your Ionic Project

  1. Install your custom plugin in the Ionic project:

npm install ./path-to-your-plugin

Call the openScreen() method from your Ionic app:
  • import { Component } from '@angular/core';
    import { FssSdkCapacitorPlugin } from 'plugins/fss-sdk-cap-plugin/src';

    @Component({
    selector: 'app-tab1',
    templateUrl: 'tab1.page.html',
    styleUrls: ['tab1.page.scss']
    })
    export class Tab1Page {

    constructor() { }
    launchSdk() {
    // FssSdkCapacitorPlugin.echo({ value: 'Hello, Plugin!' })
    // .then(result => console.log(result.value))
    // .catch(error => console.error(error));

    FssSdkCapacitorPlugin.openSdkScreen();
    }

    }

  • Test the Plugin

  • Finally, test your plugin to ensure the screen is being opened properly:

    • For Android, use the following command:

      npx cap open android
    • For iOS, use the following command:

      npx cap open ios

    Test on a physical device or emulator to confirm that the screen displays correctly when the method is called.


  • Conclusion

    Creating a custom Capacitor plugin in Ionic 7 requires setting up the plugin structure manually. By following the steps above, you can create, build, and integrate your plugin into your Ionic project. Use Capacitor's sync functionality to ensure the plugin works seamlessly across platforms.

    Comments

    Popular posts from this blog

    Google Assistant Implementation in Android application with app actions