在本教程中,我们将演示如何在 Ionic Capacitor 应用中集成 Firebase 推送通知。如需了解支持 Firebase Cloud Messaging 的维护版 Capacitor 插件,请参阅 @capgo/capacitor-firebase-messaging。你不需要专门的服务,但需要提前进行一些配置。Firebase 是一个极佳的选择,因为它在 Android 上是必需的,而且你可以轻松使用它发送通知,而无需使用数据库。
首先,我们将创建一个启用了 Capacitor 的 Ionic 应用,并指定我们的 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": {}
}
现在,让我们在 App 之外配置推送通知。
Firebase 配置
首先 创建新的 Firebase 项目 或者使用现有项目。为新项目提供名称和默认选项。
如果你有新 App,应该会看到 “将 Firebase 添加到 App 即可开始使用” ,它会在 App 的 dashboard 中显示。否则,点击齿轮图标并前往 项目设置 来添加 App。
iOS 和 Android 的对话框看起来很相似,关键是要使用你的 package id 用于应用。
完成初始步骤后,请下载以下文件:
- google-services.json Android 端文件
- GoogleService-info.plist iOS 端文件
接下来,配置各平台。
Android 推送准备
对于 Android,将 google-services.json 下载的文件移动到 android/app/ 文件夹。
Android 部分到此结束。现在让我们开始配置 iOS。
iOS 推送准备工作
这部分稍微复杂一些。首先, 在 Apple Developer 账号的标识符列表 (identifiers list) 中 为你的应用创建一个 App ID。请务必 在列表中勾选 Push Notifications 能力。

本指南中介绍的 Bundle ID 应与 Capacitor 和 Firebase 中的 App ID 保持一致。
现在, 创建一个 Key 并启用 Apple 推送通知服务 (APNs)。如果 Key 的数量已达上限,你可以使用现有的 Key 或证书,但操作会更复杂。

下载完 .p8 文件后,将其上传至 Firebase。打开 云消息传递 (Cloud Messaging) 在 Firebase 项目设置选项卡中上传该文件,并输入来自 iOS 的 Key ID 和 Team ID。

现在,通过运行以下命令来修改您的 Xcode 项目:
npx cap open ios
复制 GoogleService-Info.plist 将从 Firebase 下载的文件放入您的 iOS 项目中。将该文件拖入 Xcode 项目内的 app/app 文件夹,并选择 如果需要,请勾选 Copy items if needed.
接下来,在以下文件中为 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 注册并向您的应用返回正确的 token。
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 Notifications 能力。

现在,构建您的应用并集成推送通知。
Ionic 推送通知集成
在您的 Ionic 项目中创建一个 service 和一个新页面:
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 { }
在以下文件中创建一个处理推送通知的 service: 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();
}
}
在以下内容中显示详情 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>
构建 App,同步更改,并将其部署到设备。
ionic build
npx cap sync
现在,你可以使用 Firebase 发送推送通知了。
使用 Firebase 发送推送通知
有多种方法可以使用 Firebase 发送推送通知。
特定设备测试
将 App 部署到设备后,你可以查看控制台 logs 以获取注册后的 token。使用该 token 发送定向测试推送,以确认集成是否成功。在 Firebase 中,前往 云消息传递 (Cloud Messaging) 并选择 发送测试消息。从 logs 中添加设备 token。

如果配置正确,你应该能在设备上收到推送通知。
带 Payload 的推送消息
若要测试带有附加信息的推送通知,请按照同页面的向导填写基本信息,并选择目标平台。添加 更多选项 以便在推送通知中发送 payload。

在 高级选项 部分,添加一个 自定义数据 键值对。例如,你可以使用键 detailsId 以及你选择的值。这些数据将在 App 中用于跳转到带有指定 ID 的详情页。
发送推送通知后,App 应当能够接收它,并在用户点击通知时展示带有指定 ID 的详情页。
使用 Firebase API
你也可以通过 Firebase API 以编程方式发送推送通知。为此,你需要获取 服务器密钥 在 Firebase 项目设置的 云消息传递 (Cloud Messaging) 选项卡。
有了服务器密钥,你可以向 Firebase API 发送带有所需 payload 的 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 请使用你真实的服务器密钥和设备 token。运行该脚本,你的设备应该就能收到带有自定义 payload 的推送通知了。
大功告成!你已成功在 Ionic Capacitor 应用中通过 Firebase 集成了推送通知。现在,你可以向 Android 和 iOS 平台的用户发送推送通知了。
继续阅读 Ionic Capacitor Firebase 推送通知指南:分步教程
如果你正在使用 使用 Firebase 实现 Ionic Capacitor 推送通知:分步指南 要规划迁移和企业运营,请将其与 Capgo 企业版 用于 Capgo Enterprise 中的产品工作流, Ionic Enterprise 插件替代方案 用于 Ionic Enterprise 插件替代方案的产品工作流, Capgo 替代方案 用于 Capgo 替代方案的产品工作流, Capgo 咨询 适用于 Capgo Consulting 的产品工作流,以及 Capgo 高级支持 适用于 Capgo Premium Support 的产品工作流。