このチュートリアルでは、イオニクス Capacitor アプリにFirebaseを使用したプッシュ通知を統合します。特定のサービスは必要ありませんが、事前にいくつかの設定を実行する必要があります。Firebaseは、Androidの場合に必須であり、データベースを使用せずに通知を送信することも簡単です。
まず、Capacitor を有効にしたイオニクスアプリを作成し、 パッケージ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__に含める appIdしかし、既存のフォルダが存在する場合は、すべてのファイルでIDを置き換える必要があります。Capacitorはフォルダを作成するのみで、ID自体を更新しません。 __CAPGO_KEEP_0__.config.jsonまた、バッジの更新、プッシュ時の音の再生、通知の到着時にアラートを表示するオプションも指定できます。 capacitor.config.jsonFirebaseの設定
{
"appId": "com.appdactic.devpush",
"appName": "pushApp",
"bundledWebRuntime": false,
"npmClient": "npm",
"webDir": "www",
"plugins": {
"SplashScreen": {
"launchShowDuration": 0
},
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
},
"cordova": {}
}
まず、
新しいFirebaseプロジェクトを作成してください
__CAPGO_KEEP_0__.config.json __CAPGO_KEEP_0__ または、既存のものを使用します。新しいプロジェクトの名前とデフォルトのオプションを提供します。
新しいアプリを持っている場合、 “Get started by adding Firebase to your app” in your app’s dashboard. Otherwise, click the gear icon and go to project settings to add an app.
The dialog for both iOS and Android looks similar, and the important thing is to use your package id for the apps.
After the initial step, download the following files:
- google-services.json Android用ファイル
- __CAPGO_KEEP_0__ iOS用ファイル
次に、プラットフォームを設定します。
Android用Push準備
Androidの場合、 __CAPGO_KEEP_0__ ダウンロードしたファイルを android/app/ フォルダに移動してください。
Androidの設定は終わりました。iOSの設定に進みましょう。
iOS Push Preparation
この部分はもっと複雑です。まず、 Apple Developer アカウントの識別子リスト内でアプリのための App ID を作成してください。 App ID を作成する際には、 Push Notifications の機能をリストから選択してください。 ionic-ios-push-id

は、Apple Developer アカウントの識別子リスト内で作成した App ID と同じでなければなりません。 Capgo と Firebase 内の __CAPGO_KEEP_0__ と同じでなければなりません。 should be the same as your App ID within Capacitor and Firebase.
Key を作成してください。 __CAPGO_KEEP_0__ と、有効にする Apple Push Notificationsサービス (APNs)。最大のキーの数に達した場合、既存のキーや証明書を使用できますが、プロセスは複雑になります。

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

Xcodeプロジェクトに変更を加えるには、以下のコマンドを実行してください。
npx cap open ios
Copy the GoogleService-Info.plist __CAPGO_KEEP_0__をダウンロードしたファイルを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
ネイティブのSwift codeをiOSアプリでFirebaseと登録し、正しいトークンをアプリに返すように変更してください。 Xcodeプロジェクト内でPush通知のCapabilityを追加してください。 __CAPGO_KEEP_0__-xcode-capability
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)
}
}
}
}
アプリをビルドし、Push通知を統合してください。

Firebaseと登録し、正しいトークンをアプリに返すように変更してください。
Ionic Push Notification Integration
Ionicプロジェクトでサービスと新しいページを作成します:
ionic g service services/fcm
ionic g page pages/details
routingを更新してください 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 { }
Push通知を処理するサービスを作成します 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 __CAPGO_KEEP_0__:
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に移動し、Send test messageを選択し、ログからデバイストークンを追加してください。 Cloud Messaging Send test message FirebaseCloud Messaging

すべての設定が正しく設定されている場合、デバイス上でプッシュ通知を受信するはずです。
データを伴うプッシュ通知
追加情報を伴うプッシュ通知をテストするには、同じページのウィザードに従って、一般情報を指定し、対象とするプラットフォームを選択します。 追加オプション プッシュ通知にデータを送信するオプションを追加します。

Advanced options 高度なオプション セクションで、 カスタムデータ key-valueペアを追加します。例えば、keyを使用できます。 detailsId と選択した値を持つデータは、指定されたIDを持つ詳細ページにアプリがナビゲートするために使用されます。
プッシュ通知を送信した後、通知がタップされたときに指定されたIDを持つ詳細ページを表示するようにアプリが受信するようにしてください。
Firebase API を使用して
プッシュ通知をプログラムで送信することもできます。Firebase API を使用するには、 サーバーキー Firebase プロジェクト設定の Cloud Messaging タブの
With the server key, you can send a POST request to the Firebase API with the required payload. Here’s an example using Node.js and the request サーバーキーを使用して、Firebase __CAPGO_KEEP_0__ に必要なパイロードを含む POST リクエストを送信できます。Node.js と
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_KEEP_0__の実際のサーバーキーとデバイストークンを使用してください。スクリプトを実行し、デバイスはカスタムペイロードを含むプッシュ通知を受信するはずです。
成功しました!Ionic CapacitorアプリにFirebaseを使用してプッシュ通知を統合しました。AndroidおよびiOSプラットフォームの両方でユーザーにプッシュ通知を送信できます。
Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide
Ionic __CAPGO_KEEP_0__を使用している場合 Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide 企業運用とマイグレーション計画を行うには、__CAPGO_KEEP_0__ Enterpriseと接続してください。 Capgo Enterpriseの製品ワークフロー for the product workflow in Capgo Enterprise, __CAPGO_KEEP_0__ Alternativesの製品ワークフロー __CAPGO_KEEP_0__ Alternativesの製品ワークフロー Capgoの実際のサーバーキーとデバイストークンを使用してください。スクリプトを実行し、デバイスはカスタムペイロードを含むプッシュ通知を受信するはずです。 成功しました!Ionic CapgoアプリにFirebaseを使用してプッシュ通知を統合しました。AndroidおよびiOSプラットフォームの両方でユーザーにプッシュ通知を送信できます。 Capgo Consulting Capgo Consultingの製品ワークフローについて Capgo Premium Support Capgo Premium Supportの製品ワークフローについて