メインコンテンツへスキップ
チュートリアル

Firebaseを使ったIonic Capacitorプッシュ通知:ステップバイステップガイド

Firebaseを使ってIonic Capacitor アプリにプッシュ通知を統合する方法を、AndroidとiOSの両プラットフォーム向けのステップバイステップ手順で学びましょう。

Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide' Capgo blog illustration

本チュートリアルでは、Firebase を使用して Ionic Capacitor アプリにプッシュ通知を統合する方法を説明します。Firebase Cloud Messaging に対応したメンテナンスされている Capacitor プラグインについては、 @capgo/capacitor-firebase-messaging。特定のサービスは必要ありませんが、事前にいくつかの設定を行う必要があります。Firebase は Android に必須であり、データベースを使用せずに通知を簡単に送信できるため、優れた選択肢です。

まず、Capacitor を有効にした Ionic アプリを作成し、 パッケージID、これはアプリの一意の識別子です。次に、アプリをビルドしてネイティブプラットフォームを追加します。

ionic start pushApp blank --type=angular --capacitor --package-id=com.appdactic.devpush
cd ./pushApp
ionic build
npx cap add ios
npx cap add android

既存のアプリがある場合は、 capacitor.config.json を変更して appIdを含めることができます。ただし、ネイティブフォルダが既に存在する場合は、Capacitor はフォルダを一度だけ作成し、 id 自体は更新しないため。 capacitor.config.jsonでは、バッジカウントの更新、プッシュ時のサウンド再生、通知受信時のアラート表示などのオプションも指定できます。

{
  "appId": "com.appdactic.devpush",
  "appName": "pushApp",
  "bundledWebRuntime": false,
  "npmClient": "npm",
  "webDir": "www",
  "plugins": {
    "SplashScreen": {
      "launchShowDuration": 0
    },
    "PushNotifications": {
      "presentationOptions": ["badge", "sound", "alert"]
    }
  },
  "cordova": {}
}

それでは、アプリ外でのプッシュ通知の設定を進めましょう。

Firebaseの設定

まずは、 新しいFirebaseプロジェクトの作成 または既存のプロジェクトを使用します。新しいプロジェクトの場合は、名前とデフォルトのオプションを入力してください。

新しいアプリの場合は、アプリのダッシュボードに 「アプリにFirebaseを追加して開始」 と表示されます。表示されていない場合は、歯車アイコンをクリックして プロジェクトの設定 からアプリを追加してください。

iOSとAndroidのダイアログは似ていますが、重要なのは パッケージID アプリ向けに。

firebase-app-setup-ios

最初のステップが完了したら、以下のファイルをダウンロードしてください:

  • google-services.json Android 用のファイル
  • GoogleService-info.plist iOS 用のファイル

次に、プラットフォームを設定します。

Androidのプッシュ通知準備

Android の場合は、 google-services.json ダウンロードしたファイルを android/app/ フォルダ。

android-push-file

Android の設定は以上です。次に iOS を設定しましょう。

iOSのプッシュ通知準備

この部分は少し複雑です。まず、 Apple Developer アカウントの identifiers リスト内でアプリの App ID を作成します。 必ず Push Notifications capability を リストから選択してください。

ionic-ios-push-id

この Bundle ID は、Capacitor と Firebase の App ID と同じである必要があります。

次に、 Key を作成し、 次を有効にします: Apple Push Notifications service (APNs)。Key の上限に達している場合は、既存の Key や証明書で代用できますが、手順はより複雑になります。

ios-developer-push-key

をダウンロードしたら、 .p8 ファイルを Firebase に upload してください。次に、 Cloud Messaging Firebase プロジェクト設定のタブでファイルをアップロードし、iOS の Key ID と Team ID の詳細を入力します。

firebase-upload-ios-key

次に、以下のコマンドを実行して Xcode プロジェクトを変更します:

npx cap open ios

以下をコピー GoogleService-Info.plist Firebase からダウンロードしたファイルを iOS プロジェクトに追加します。ファイルを app/app フォルダ内の Xcode プロジェクトにドラッグし、 必要に応じてアイテムをコピー.

次に、Firebase 依存関係用の新しい Pod を ios/App/Podfile:

target 'App' do
  capacitor_pods
  # Add your Pods here
  pod 'Firebase/Messaging'
end

以下のコマンドでネイティブプラットフォームを更新します:

npx cap update ios

以下のファイル内のネイティブ Swift code を修正します: ios/App/App/AppDelegate.swift Firebaseに登録し、アプリに正しいトークンを返します。

import UIKit
import Capacitor
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    return true
  }

  // All the existing functions
  // ...

  // Update this one:
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidFailToRegisterForRemoteNotificationsWithError.name()), object: error)
            } else if let result = result {
                NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidRegisterForRemoteNotificationsWithDeviceToken.name()), object: result.token)
            }
        }
    }
}

最後に、Xcodeプロジェクト内でPush NotificationsのCapabilityを追加します。

capacitor-xcode-capability

では、アプリをビルドしてプッシュ通知を統合しましょう。

Ionicでのプッシュ通知の統合

Ionicプロジェクト内に、サービスと新しいページを作成します:

ionic g service services/fcm
ionic g page pages/details

ルーティングを更新します: app/app-routing.module.ts 動的なIDを持つ新しいページを追加します:

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home/:id',
    loadChildren: () => import('./pages/details/details.module').then( m => m.DetailsPageModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

プッシュ通知を処理するサービスを以下に作成します: services/fcm.service.ts:

import { Injectable } from '@angular/core';
import {
  Plugins,
  PushNotification,
  PushNotificationToken,
  PushNotificationActionPerformed,
  Capacitor
} from '@capacitor/core';
import { Router } from '@angular/router';

const { PushNotifications } = Plugins;

@Injectable({
  providedIn: 'root'
})
export class FcmService {

  constructor(private router: Router) { }

  initPush() {
    if (Capacitor.platform !== 'web') {
      this.registerPush();
    }
  }

  private registerPush() {
    PushNotifications.requestPermission().then((permission) => {
      if (permission.granted) {
        // Register with Apple / Google to receive push via APNS/FCM
        PushNotifications.register();
      } else {
        // No permission for push granted
      }
    });

    PushNotifications.addListener(
      'registration',
      (token: PushNotificationToken) => {
        console.log('My token: ' + JSON.stringify(token));
      }
    );

    PushNotifications.addListener('registrationError', (error: any) => {
      console.log('Error: ' + JSON.stringify(error));
    });

    PushNotifications.addListener(
      'pushNotificationReceived',
      async (notification: PushNotification) => {
        console.log('Push received: ' + JSON.stringify(notification));
      }
    );

    PushNotifications.addListener(
      'pushNotificationActionPerformed',
      async (notification: PushNotificationActionPerformed) => {
        const data = notification.notification.data;
        console.log('Action performed: ' + JSON.stringify(notification.notification));
        if (data.detailsId) {
          this.router.navigateByUrl(`/home/${data.detailsId}`);
        }
      }
    );
  }
}

以下を呼び出します: initPush() function in app/app.component.ts:

import { Component } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { FcmService } from './services/fcm.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private fcmService: FcmService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      // Trigger the push setup
      this.fcmService.initPush();
    });
  }
}

詳細ページで情報を処理するには pages/details/details.page.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Plugins } from '@capacitor/core';
const { PushNotifications } = Plugins;

@Component({
  selector: 'app-details',
  templateUrl: './details.page.html',
  styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {
  id = null;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
    });
  }

  resetBadgeCount() {
    PushNotifications.removeAllDeliveredNotifications();
  }

}

詳細を表示するには pages/details/details.page.html:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/"></ion-back-button>
    </ion-buttons>
    <ion-title>Details</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  My Id from push: {{ id }}

  <ion-button (click)="resetBadgeCount()" expand="block">
    Reset Badge Count
  </ion-button>
</ion-content>

アプリをビルドし、変更を同期して、デバイスにデプロイします。

ionic build
npx cap sync

これで、Firebase を使ってプッシュ通知を送信できます。

Firebaseによるプッシュ通知の送信

Firebase を使ってプッシュ通知を送信する方法はいくつかあります。

特定のデバイスでのテスト

アプリをデバイスにデプロイした後、コンソールのログを確認して、登録後のトークンを確認できます。このトークンを使用して、ターゲットを絞ったテストプッシュを送信し、統合が正常に動作していることを確認してください。Firebase で、 Cloud Messaging を選択し、 テストメッセージを送信。ログからデバイストークンを追加してください。

firebase-test-push

設定が正しく完了していれば、デバイスにプッシュ通知が表示されます。

ペイロード付きプッシュメッセージ

追加情報を含むプッシュ通知をテストするには、同じページにあるウィザードに従って基本情報を指定し、対象のプラットフォームを選択してください。次に、 詳細オプション を追加して、プッシュ通知にペイロードを付けて送信します。

firebase-push-payload

では 詳細オプション セクションに追加 カスタムデータ キーと値のペアです。例えば、キーに detailsId 、値に任意の値を設定できます。このデータはアプリ内で使用され、指定されたIDの詳細ページへ遷移します。

プッシュ通知を送信した後、アプリが通知を受信し、通知をタップすると指定されたIDの詳細ページが表示されるはずです。

Firebase API を使う

Firebase API を使用して、プログラムからプッシュ通知を送信することもできます。これには、 サーバーキー をFirebaseプロジェクト設定の Cloud Messaging タブと比較してください。

サーバーキーを使えば、必要なペイロードを付けて Firebase API に POST リクエストを送信できます。以下は Node.js と次の request ライブラリを使った例です:

const request = require('request');

const serverKey = 'YOUR_SERVER_KEY';
const deviceToken = 'YOUR_DEVICE_TOKEN';

const options = {
  method: 'POST',
  url: 'https://fcm.googleapis.com/fcm/send',
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'key=' + serverKey
  },
  body: JSON.stringify({
    to: deviceToken,
    notification: {
      title: 'Test Push',
      body: 'This is a test push notification with custom data'
    },
    data: {
      detailsId: '123'
    }
  })
};

request(options, (error, response, body) => {
  if (error) {
    console.error('Error sending push:', error);
  } else {
    console.log('Push sent successfully:', body);
  }
});

置換する YOUR_SERVER_KEY および YOUR_DEVICE_TOKEN 実際のサーバーキーとデバイストークンに置き換えてください。スクリプトを実行すると、デバイスにカスタムペイロード付きのプッシュ通知が届くはずです。

完了です!Firebase を使って、Ionic Capacitor アプリにプッシュ通知を実装できました。これで、Android と iOS の両方でユーザーにプッシュ通知を送信できます。

続きを読む:Ionic Capacitor のFirebaseプッシュ通知ステップバイステップガイド

使用している場合 Firebaseを使ったIonic Capacitorプッシュ通知:ステップバイステップガイド 移行とエンタープライズ運用を計画するには、次と連携してください Capgo エンタープライズ Capgo Enterprise のプロダクトワークフロー向けに、 Ionic Enterprise プラグインの代替案 Ionic Enterprise Plugin Alternatives のプロダクトワークフロー向けに、 Capgo の代替案 Capgo Alternatives でのプロダクトワークフロー向け、 Capgo コンサルティング Capgo Consulting でのプロダクトワークフロー向け、および Capgo プレミアムサポート Capgo Premium Support でのプロダクトワークフロー向け。

Capacitor アプリ向けの Live Updates

Web レイヤーのバグが本番で発生したら、App Store の審査を何日も待たずに Capgo で修正を配信しましょう。ネイティブの変更は通常の審査フローに残したまま、ユーザーはバックグラウンドでアップデートを受け取れます。

最新のブログ記事

Capgoは、真にプロフェッショナルなモバイルアプリを作るために必要な最高のインサイトを提供します。