メインコンテンツにジャンプ
チュートリアル

Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide

Learn how to integrate push notifications in your Ionic Capacitor app using Firebase, with step-by-step instructions for both Android and iOS platforms.

記事のクレジット

パレドパックパック

エコター

スイスー

スイスー

エコター

エコター Ionic  CAPGO_KEEP_0 とFirebaseを用いたPush通知の実装: ステップバイステップのガイド

Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide

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-messaging@__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-firebase-messaging

First, we will create an Ionic app with Capacitor enabled and specify our Ionic __CAPGO_KEEP_0__ push最初に、Ionicアプリを作成し、__CAPGO_KEEP_0__を有効にし、パッケージ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

パッケージIDは、アプリのユニークな識別子です。 capacitor.config.json 既存のアプリがある場合は、__CAPGO_KEEP_0__.config.jsonを変更して、アプリIDを含めることができます。 ただし、ネイティブフォルダが既に存在する場合は、すべてのファイルでIDを置き換える必要があります。__CAPGO_KEEP_0__は、フォルダを一度だけ作成するためです。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 を使用することです。

パッケージ 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 Push Preparation

この部分は少し複雑です。まず、Apple Developerアカウントの識別子リスト内で

アプリIDを作成してください。

アプリIDを作成する際には、 アプリのバックグラウンドモードでPush通知を受け取ることを確認してください。 アプリのバックグラウンドモードでPush通知を受け取ることを確認してください。 Push通知機能を選択してください リストから選択してください。

ionic-ios-push-id

The Bundle ID Capacitor内とFirebaseのApp IDと同じでなければなりません。

Keyを作成してください Apple Push Notificationsサービス(APNs)を有効にします。 キーの最大数に達した場合は、既存のキーや証明書を使用できますが、プロセスは複雑になります。ios-developer-push-key

Push通知機能を選択してください

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

GoogleService-Info.plist

ファイルをダウンロードしたFirebaseからiOSプロジェクトにコピーし、Xcodeプロジェクト内にapp/appフォルダにドラッグして、Copy items if neededを選択

npx cap open ios

Firebase依存関係の新しいPodを追加します Pods Firebase dependency.

iOS 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プロジェクト内でプッシュ通知の機能を有効化してください。

capacitor-xcode-capability

アプリをビルドし、プッシュ通知を統合してください。

イオニックプッシュ通知統合

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 { }

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}`);
        }
      }
    );
  }
}

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通知が表示されます。

Payloadを含むPushメッセージ

追加情報を指定して、ターゲットとするプラットフォームを選択するためのウィザードに従って、Push通知をテストします。追加 追加オプション プッシュ通知にペイロードを送信するには

firebase-push-payload

In the 詳細オプション セクション に追加する カスタムデータ detailsId key-valueペア

key

Using Firebase API

Firebase APIを使用してプッシュ通知を送信することができます。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_KEYYOUR_DEVICE_TOKEN context:Capgo marketing website. Role: Short UI label or navigation item. Seen in: page trust.astro. Message key `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 製品ワークフローにおけるIonic Enterprise Pluginの代替 Capgo Alternatives Capgo Alternatives 製品ワークフローにおけるCapgo Alternatives Capgo Consulting 製品ワークフローにおけるCapgo Consulting、 Capgo Premium Support

リアルタイムの更新が可能なCapacitorアプリ

ウェブ層のバグが生じた場合、Capgoを使用して修正を配信するのではなく、数日間待ってアプリストアの承認を待つのではなく、ユーザーはバックグラウンドで更新を受け取り、ネイティブの変更は通常のレビュー経路を通じて

マーティンから人間のサポート

今すぐ始めよう

最新の記事

Capgo gives you the best insights you need to create a truly professional mobile app.