このチュートリアルでは、Firebaseを使用してIonic Capacitor アプリにPush Notificationsを統合する方法を解説します。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を設定してください。ただし、すでにネイティブフォルダが存在する場合は、すべてのファイル内のIDを手動で置換する必要があります。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 アプリ向けに。
最初のステップが完了したら、以下のファイルをダウンロードしてください:
- google-services.json Android 用のファイル
- GoogleService-info.plist iOS 用のファイル
次に、プラットフォームを設定します。
Androidのプッシュ通知準備
Android の場合は、 google-services.json ダウンロードしたファイルを android/app/ フォルダ。
Androidの設定は以上です。次にiOSの設定を行いましょう。
iOSのプッシュ通知準備
iOSの設定は少し複雑です。まず、 Apple DeveloperアカウントのIdentifiersリストから、 アプリ用のApp IDを作成してください。 その際、リストの中から Push NotificationsのCapabilityを必ず選択してください。

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

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

次に、以下のコマンドを実行してXcodeプロジェクトに変更を適用します:
npx cap open ios
以下をコピー GoogleService-Info.plist FirebaseからダウンロードしたファイルをiOSプロジェクトに追加します。ファイルをXcodeプロジェクト内のapp/appフォルダにドラッグし、以下を選択してください: 必要に応じて項目をコピー.
次に、Firebaseの依存関係のために新しいPodを以下に追加します: ios/App/Podfile:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
次のコマンドでネイティブプラットフォームを更新します:
npx cap update ios
ios/App/App/AppDelegate.swift 内のネイティブ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を追加します。

では、アプリをビルドしてプッシュ通知を統合しましょう。
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() 内の関数 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 を選択し、 テストメッセージを送信。ログからデバイストークンを追加してください。

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

では 詳細設定 セクションに、 カスタムデータ のキーと値のペアを追加します。例えば、キーに 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 でのプロダクトワークフロー向け。