4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ionic Native Plugin を自作する

4
Last updated at Posted at 2020-09-17

携わっているプロジェクトで使用することになったのでメモがてら

Cordova Plugin の作成

ディレクトリ作成

プラグイン開発は以下のフォルダ構成で行います。

フォルダ構成
./custom_plugins
└── cordova-plugin-helloworld
    ├── package.json
    ├── plugin.xml
    ├── src
    │   ├── android
    │   │   └── HelloWorld.java
    │   └── ios
    │       └── HelloWorld.swift
    └── www
        └── helloworld.js

package.json の作成

package.json の内容は以下の通りです。

package.json
{
  "name": "cordova-plugin-helloworld",
  "version": "1.0.0",
  "cordova": {
    "id": "cordova-plugin-helloworld",
    "platforms": [
      "android",
      "ios"
    ]
  }
}

plugin.xml の作成

plugin.xml
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
  xmlns:android="http://schemas.android.com/apk/res/android"
  id="cordova-plugin-helloworld"
  version="1.0.0">

  <name>HelloWorld</name>
  <description>HelloWorld!!!</description>
  <license>HogeLicense</license>
  <engines>
    <engine name="cordova-android" version=">5.0.0"/>
  </engines>
  <js-module src="www/helloworld.js" name="HelloWorld">
    <clobbers target="HelloWorld"/>
  </js-module>

  <platform name="ios">
    <config-file target="config.xml" parent="/*">
      <feature name="HelloWorld">
        <param name="ios-package" value="HelloWorld" onload="true" />
      </feature>
    </config-file>
    <source-file src="src/ios/HelloWorld.swift" />
  </platform>

  <platform name="android">
    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="helloworld">
        <param name="android-package" value="plugin.helloworld.HelloWorld"/>
      </feature>
    </config-file>
    <source-file src="src/android/HelloWorld.java" target-dir="src/plugin/helloworld/"/>
  </platform>
</plugin>

helloworld.js の作成

helloworld.js
var exec = require("cordova/exec");

module.exports = {
  echo: function (name, successCallback, errorCallback) {
    exec(successCallback, errorCallback, "helloworld", "echo", [name]);
  },
};

HelloWorld.java の作成(Android Native)

HelloWorld.java
package plugin.helloworld;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;

public class HelloWorld extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {

        if (action.equals("echo")) {
            String name = data.getString(0);
            String message = "Hello, World !!! " + "Hello, " + name;
            callbackContext.success(message);
            return true;
        } else {
            return false;
        }
    }
}

HelloWorld.swift の作成(iOS Native)

HelloWorld.swift
import Foundation
import UIKit

@objc(HelloWorld) class HelloWorld: CDVPlugin {
    @objc(echo:)
    func echo(command: CDVInvokedUrlCommand) {

        let name = command.arguments.first as! String
        let message = "Hello, World !!! " + "Hello, " + name;

        let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)

        self.commandDelegate!.send(result, callbackId: command.callbackId)

    }
}

一旦作成した Plugin を使ってみる

空の Ionic プロジェクトを作成し、上記で作成したプラグインを add する

$ ionic start plugin-test blank
$ cd plugin-test

プラグインの追加

$ ionic cordova plugin add ./custom_plugins/cordova-plugin-helloworld

アプリ側にプラグインの実行処理を実装

home.page.ts
import { Component } from "@angular/core";
import { Platform } from "@ionic/angular";

declare var HelloWorld: any;

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"],
})
export class HomePage {
  constructor(public platform: Platform) {
    this.platform.ready().then(() => {
      HelloWorld.echo("MyName", this.successCallback, this.errorCallback);
    });
  }
  successCallback(message) {
    alert(message);
  }
  errorCallback() {
    alert("hello error");
  }
}

Platform の追加と実行

$ ionic cordova platform add android
$ ionic cordova platform add ios
$ ionic cordova run android
$ ionic cordova run ios

Ionic native plugin の作成

準備

$ git clone https://github.com/ionic-team/ionic-native.git
$ rm -rf ionic-native/src/@ionic-native/plugins/*

Native Plugin 用のファイルの生成

$ cd ionic-native
$ npm install
$ gulp plugin:create -n HelloWorldPlugin

プラグインの定義部分を変更:

src/@ionic-native/plugins/hello-world-plugin/index.ts
@Plugin({
  pluginName: 'HelloWorldPlugin',
  plugin: 'cordova-plugin-helloworld',
  pluginRef: 'HelloWorldPlugin',
  platforms: ['Android', 'iOS'],
})

メソッドを追加:

@Injectable()
export class HelloWorldPlugin extends IonicNativePlugin {
  @Cordova()
  echo(arg1: string): Promise<any> {
    return;
  }
}

Native Plugin のビルド

$ npm run build

Native Plugin のインストール

$ npm install --save path/to/ionic-native/dist/\@ionic-native/hello-world-plugin

呼び出しコードを修正

home.page.ts
import { Component } from "@angular/core";
import { Platform } from "@ionic/angular";
import { HelloWorldPlugin } from "@ionic-native/hello-world-plugin/ngx";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"],
})
export class HomePage {
  constructor(public platform: Platform, public helloworld: HelloWorldPlugin) {
    this.platform.ready().then(() => {
      this.helloworld.echo("ACN").then((message) => {
        this.successCallback(message);
      });
    });
  }
  successCallback(message) {
    alert(message);
  }
  errorCallback() {
    alert("hello error");
  }
}

Git

ここにコード置いてます

参考

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?