跳过主要内容
教程

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.

文章贡献者

马丁·多纳迪尤

作者

瓦莱里亚

审阅者

乔丹

Editor

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.您不需要特定的服务,但您需要在此之前配置几个东西。 Firebase 是一个优秀的选择,因为它是 Android 所必需的,并且您可以轻松使用它来发送通知,而无需使用数据库。

First, we will create an Ionic app with Capacitor enabled and specify our 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 以包含您的 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 为应用

firebase-app-setup-ios

完成初始步骤后,请下载以下文件:

  • google-services.json 文件(适用于 Android)
  • GoogleService-info.plist iOS 文件

接下来,配置平台。

Android 推送准备

对于 Android,移动您下载的 google-services.json 文件到 android/app/ 文件夹。

android-push-file

Android 的所有工作都完成了。现在,让我们配置 iOS。

iOS 推送准备

这个部分更复杂。首先, 在标识符列表中为您的应用创建一个 App ID 您的 Apple 开发者帐户中。确保您 从列表中选择 Push 通知功能 从列表中选择

ionic-ios-push-id

The Bundle ID 应与您的 App ID 在 Capacitor 和 Firebase 中保持一致

现在 创建一个密钥 并启用 Apple Push 通知服务 (APNs) 从列表中如果您已经达到最大密钥数量,需要使用现有的密钥或证书,但该过程更为复杂。

ios-developer-push-key

下载后 .p8 在 Appflow 中,Capgo 提供了更简单的流程来获取推送通知密钥。 Capgo 的 Appflow 凭证流程更为简单,易于使用。 文件,上传到 Firebase。打开 Firebase 项目设置中的

Cloud Messaging

选项卡,上传文件并输入 iOS 中的 Key ID 和 Team ID 详情。

npx cap open ios

firebase-upload-ios-key 现在,请在 Xcode 项目中运行以下命令: 复制您从 Firebase 下载的 如需复制项.

接下来,在 ios/App/Podfile:

target 'App' do
  capacitor_pods
  # Add your Pods here
  pod 'Firebase/Messaging'
end

更新本地平台使用以下命令:

npx cap update ios

Modify the native Swift code in 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项目中创建一个服务和一个新页面:

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

}

中处理详细信息 :

<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 并选择 发送测试消息。将设备令牌从日志中添加。

firebase-test-push

如果设置正确,应在您的设备上看到推送通知。

推送消息

为了测试带有额外信息的推送通知,请在同一页面上遵循向导,指定一般信息并选择要目标的平台。添加 额外选项 以发送带有推送通知的负载。

firebase-push-payload

高级选项 部分,添加一个 自定义数据 键值对。例如,您可以使用键 detailsId 并选择一个值。这条数据将在应用中用来导航到带有指定ID的详细页面。

发送推送通知后,应用应该接收到它并在点击通知时显示带有指定ID的详细页面。

使用 Firebase API

您还可以使用 Firebase API 以编程方式发送推送通知。要实现此功能,您需要从 Firebase 项目设置中获取 服务器密钥 从您的 Firebase 项目设置中的 云消息 选项卡中获取。

使用服务器密钥,您可以将所需的负载发送到 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

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: 步骤指南

如果您正在使用 Ionic Capacitor 推送通知与 Firebase: 步骤指南 来规划迁移和企业运营,连接它与 Capgo 企业 for the product workflow in Capgo Enterprise, 用于产品工作流程中的__CAPGO_KEEP_0__ 企业 Ionic 企业插件替代品 Capgo Alternatives Capgo 替代品 用于产品工作流程中的Capgo 替代品 Capgo 咨询服务 Capgo 高级支持 为产品工作流程提供 Capgo 高级支持。

Live updates for Capacitor apps

当 web 层面的 bug 活跃时,通过 Capgo 发送修复而不是等待几天的 app store 审核。用户在后台接收更新,而原生变化仍然在正常的审查路径中。

来自 Martin 的人性化支持

立即开始

最新博客文章

Capgo 为您提供了创建真正专业的移动应用所需的最佳见解。