このチュートリアルでは、Ionic Capacitor アプリに Firebase を使用してプッシュ通知を統合するステップバイステップのガイドを紹介します。
ionic Capacitor push まず、Ionic アプリを作成し、__CAPGO_KEEP_0__ を有効にし、package 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 __CAPGO_KEEP_0__.config.json を変更して、アプリIDを含めることができます。. ただし、既存のフォルダが存在する場合は、すべてのファイルで Capacitor で作成されたフォルダの id を置き換える必要があります。 id 自身を更新しないためです。. __CAPGO_KEEP_0__.config.json 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
次に、プラットフォームを設定します。
Android Push の準備
Android の場合、ダウンロードした __CAPGO_KEEP_0__ ファイルを __CAPGO_KEEP_1__ フォルダに移動してください。
Android の設定は終わりです。iOS を設定しましょう。
iOS Push の準備
この部分は複雑です。まず、 __CAPGO_KEEP_3__ Apple Developer アカウントのうちの Push Notifications の機能をリストから選択してください。 ionic-ios-push-id

Capgo と Firebase の App ID と同じでなければなりません。 Key should be the same as your App ID within Capacitor and Firebase.
キーの最大数に達した場合は、既存のキーや証明書を使用できますが、プロセスは複雑になります。 __CAPGO_KEEP_0__

Capgoのダウンロードが完了した後、Firebaseにファイルをアップロードしてください。 Firebaseのプロジェクト設定でCloud Messagingタブを開き、ファイルをアップロードし、Key IDとTeam IDの詳細を入力してください。 firebase-upload-ios-key Xcodeプロジェクトに変更を加えるには、以下のコマンドを実行してください。 Copy the GoogleService-Info.plist

Capgo
npx cap open ios
Capacitor GitHub Cloud Messaging SDK.
次に、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)
}
}
}
}
__CAPGO_KEEP_0__-xcode-capability

Push Notificationの統合
Ionicプロジェクトでサービスと新しいページを作成します。
ルーティングを更新します。
ionic g service services/fcm
ionic g page pages/details
アプリをビルドし、プッシュ通知を統合します。 app/app-routing.module.ts __CAPGO_KEEP_0__を含む新しいページを動的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 { }
__CAPGO_KEEP_0__を動的IDで追加するサービスを作成する: Push通知を処理するサービスを作成する::
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}`);
}
}
);
}
}
__CAPGO_KEEP_0__を呼び出す: initPush() __CAPGO_KEEP_0__の関数を呼び出す: 詳細ページの情報を処理する::
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();
});
}
}
詳細ページで情報を表示する: 詳細ページのHTMLで情報を表示する::
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();
}
}
アプリをビルドし、変更を同期し、デバイスにデプロイする: __CAPGO_KEEP_0__:
<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>
__CAPGO_KEEP_0__
ionic build
npx cap sync
現在、Firebaseでプッシュ通知を送信できます。
Firebaseでプッシュ通知を送信する
Firebaseでプッシュ通知を送信する方法は複数あります。
特定のデバイスのテスト
アプリをデバイスにデプロイした後、登録後のトークンを確認するコンソールログを確認できます。このトークンを使用して、確認用のターゲットテストプッシュを送信して、インテグレーションが正常に動作していることを確認します。Firebaseの Cloud Messaging に移動し、 Send test messageに移動してください。ログからデバイスのトークンを追加してください。

すべての設定が正しく設定されている場合、デバイス上でプッシュ通知を確認できます。
ペイロードを含むプッシュメッセージ
追加情報を含むプッシュ通知をテストするには、同じページでウィザードを実行して一般情報を指定し、ターゲットとするプラットフォームを選択します。 追加のオプション プッシュ通知にペイロードを送信するオプションを追加します。

「詳細設定」セクションで、 高度なオプション セクションで、 カスタムデータ キー値ペアを追加します。例えば、キー detailsId と任意の値を使用できます。このデータは、指定されたIDで詳細ページに移動するためにアプリ内で使用されます。
プッシュ通知を送信した後、アプリは指定されたIDで詳細ページを表示するように設計されているため、プッシュ通知がタップされたときに指定されたIDで詳細ページを表示するように設計されているはずです。
Firebase API
プログラムでプッシュ通知を送信することもできます。FirebaseのAPIを使用してください。 Server key 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 スクリプトを実行すると、デバイスにカスタムパayloadを含むプッシュ通知が届きます。 YOUR_DEVICE_TOKEN 完了!Ionicの__CAPGO_KEEP_0__アプリにFirebaseを使用してプッシュ通知を統合しました。
That’s it! You’ve successfully integrated push notifications in your Ionic Capacitor app using Firebase. Now you can send push notifications to your users on both Android and iOS platforms.