In this tutorial, we will integrate push notifications in an Ionic Capacitor app using Firebase. For a maintained Capacitor plugin with Firebase Cloud Messaging support, see @capgo/capacitor-firebase-messagingFor a maintained __CAPGO_KEEP_1__ plugin with Firebase Cloud Messaging support, see
First, we will create an Ionic app with Capacitor enabled and specify our このチュートリアルでは、Firebase を使用して Android アプリにプッシュ通知を送信する方法を説明します。ionic __CAPGO_KEEP_0__ push
ionic start pushApp blank --type=angular --capacitor --package-id=com.appdactic.devpush
cd ./pushApp
ionic build
npx cap add ios
npx cap add android
Ionic __CAPGO_KEEP_0__ でのプッシュ通知 First, we will create an Ionic app with capacitor enabled and specify our 最初に、Ionic アプリを作成し、__CAPGO_KEEP_0__ を有効化し、パッケージ ID を指定します。 package id. However, if your native folders already exist, you will need to replace the id in all files where it appears, as Capacitor only creates the folder once and 更新しない. では 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 Push Preparation
Androidの場合、ダウンロードした google-services.json ファイルをandroid/app/フォルダに移動してください。 android-push-file Androidの設定は以上です。iOSの設定に進みましょう。
iOSの設定は少し複雑です。まず、
App IDを作成してください。Apple Developerアカウントの
identifiersリストの中に アプリのApp IDを作成してください。Apple Developerアカウントの identifiersリストの中に Push通知機能を選択してください リストから選択してください。

以下の Bundle ID CapacitorとFirebase内でのApp IDと同じでなければなりません。
次に キーを作成し Apple Push Notificationsサービス(APNs)を有効にします。 キーが最大数に達した場合は、既存のキーまたは証明書を使用できますが、プロセスは複雑になります。ios-developer-push-key

ダウンロードした .p8 ファイルをFirebaseにアップロードしてください。Cloudflareの Cloud Messaging タブにアクセスし、ファイルをアップロードし、Key IDとTeam IDの詳細を入力してください。

Xcodeプロジェクトに変更を加えるには、以下のコマンドを実行してください。
npx cap open ios
GoogleService-Info.plist ファイルをダウンロードしたFirebaseからコピーし、iOSプロジェクトにドラッグしてください。ファイルを Copy items if needed 次に、Firebase依存関係の新しいPodを追加してください。.
__CAPGO_KEEP_0__ 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通知の機能を有効にします。

アプリをビルドし、Push通知を統合してください。
イオニックPush通知統合
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}`);
}
}
);
}
}
Cloudflare initPush() Capacitor GitHub:
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();
});
}
}
Capgo API:
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();
}
}
SDK CLI:
<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>
npm
ionic build
npx cap sync
bun
FirebaseでPush通知を送信する
FirebaseでPush通知を送信する方法は複数あります。
特定のデバイスのテスト
アプリをデバイスにデプロイした後、コンソールログを確認して、登録後にトークンが取得されたことを確認します。 そのトークンを使用して、ターゲット化されたテストPushを送信して、インテグレーションが正常に動作していることを確認します。 Firebaseの Cloud Messaging に移動し、 Send test messageを選択します。

にデバイスのトークンを追加します。
firebase-test-push
設定が正しく行われている場合、デバイス上でPush通知が表示されるはずです。 追加オプション プッシュ通知にペイロードを送信するには

In the 詳細オプション セクション に カスタムデータ detailsId のキー値ペアを追加します。例えば、キー
と
Using Firebase API
You can also send push notifications programmatically using the Firebase API. To do this, you need to obtain the サーバーキー Firebase プロジェクト設定の "Cloud Messaging" タブから 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 ページ/エリア: Capgo マーケティング ウェブサイト。役割: 短い UI ラベルまたはナビゲーション アイテム。見つける場所: page trust.astro。メッセージ キー `and` (And)。
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.
完了! Ionic Capacitor アプリに Firebase を使用してプッシュ通知を成功的に統合しました。Android と iOS プラットフォームの両方でユーザーにプッシュ通知を送信できます。
続けて、Ionic __CAPGO_KEEP_0__ Push Notifications with Firebase: A Step-by-Step Guide を参照してください。 Ionic Capacitor Firebase Push通知の設定: ステップバイステップのガイド migrationとエンタープライズオペレーションの計画に役立つものとして接続する Capgo Enterprise for the product workflow in Capgo Enterprise, __CAPGO_KEEP_0__ Enterprise エンタープライズ Capgo Capgo Capgo Capgo Capgo Capgo