本教程中,我们将在Ionic Capacitor 应用中集成推送通知使用 Firebase。您不需要为此使用特定的服务,但您需要在事先配置几个东西。Firebase 是一个优秀的选择,因为它是 Android 所必需的,并且您可以轻松使用它来发送通知而不使用数据库。
首先,我们将创建一个 Ionic 应用程序,并启用 Capacitor,并指定我们的 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 项目 或使用现有的一个。为新项目提供一个名称和默认选项。
如果您有一个新应用程序,则应在应用程序的控制台中看到 “Get started by adding Firebase to your app” 在项目设置中点击齿轮图标并添加应用程序。 如果您有一个新应用程序,则应在应用程序的控制台中看到 to add an app.
iOS 和 Android 的对话框看起来很相似,重要的是要使用你的 __CAPGO_KEEP_0__ firebase-app-setup-ios
google-services.json
- Android 的 GoogleService-info.plist
- iOS 的 Android 平台配置
对于 Android,移动
Android 推送准备
For Android, move the google-services.json __CAPGO_KEEP_0__ android/app/ folder.
Android配置完成。现在让我们配置iOS。
iOS推送准备
这个部分更复杂。首先,在您的Apple Developer帐户的标识符列表中 为您的应用创建一个App ID。确保您 从列表中选择推送通知功能 android-push-file Android配置完成。现在让我们配置iOS。

The 学除 ID should be the same as your App ID within Capacitor and Firebase.
初始一个服务窗。当前。 当前学除窗。当前学除窗。当前学除窗。当前学除窗。 学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。 学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。

学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。 学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。学除窗。 将文件上传到 Firebase。打开 Firebase 项目设置中的 "Cloud Messaging" 选项卡,上传文件,并输入从 iOS 中的 Key ID 和 Team ID 的详细信息。 Cloud Messaging 现在,通过运行:

GoogleService-Info.plist
npx cap open ios
文件并将其拖放到 iOS 项目中,选择 Copy items if needed 接下来,在 ios/App/Podfile.
更新本机平台使用以下命令: firebase-upload-ios-key:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
Copy the "GoogleService-Info.plist" file you downloaded from Firebase into your iOS project. Drag the file into the Xcode project inside the app/app folder, and select "Copy items if needed".
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 项目中添加推送通知的能力。

现在,构建您的应用并集成推送通知。
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();
}
}
页面显示详细信息 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.将设备令牌从日志中添加到

如果一切设置正确,您应该在设备上看到一个推送通知。
带有载荷的推送消息
要测试带有额外信息的推送通知,请遵循同一页面上的向导,指定一般信息并选择要目标的平台。添加 additional options 以将载荷与推送通知一起发送。

在 高级选项 部分,添加一个 自定义数据 键值对。例如,您可以使用键 detailsId 并选择一个值。这段数据将用于在应用中导航到指定id的详细页面。
在接收推送通知后,应用程序应该接收它并在点击通知时显示指定id的详细页面。
使用 Firebase API
您还可以使用 Firebase API 程序matic地发送推送通知。要实现此功能,您需要从 Firebase 项目设置中获取 服务器密钥 ,然后在 Firebase 项目设置下 云消息推送 tab.
使用服务器密钥,您可以向 Firebase API 发送一个 POST 请求,带上所需的 payload。以下是使用 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 使用您的实际服务器密钥和设备令牌。运行脚本,设备应该会接收到带有自定义 payload 的推送通知。
就这样!您已经成功在 Ionic Capacitor 应用中集成 Firebase 推送通知。现在您可以在 Android 和 iOS 平台上向用户发送推送通知。
继续 Ionic Capacitor Push Notifications with Firebase:一步步指南
如果您正在使用 Ionic Capacitor Push Notifications with Firebase:一步步指南 来规划迁移和企业运营,连接它 Capgo 企业版 为 Capgo 企业版中的产品工作流程 Ionic 企业插件替代品 为 Ionic 企业插件替代品中的产品工作流程 Capgo 替代品 为 Capgo 替代品中的产品工作流程 Capgo 咨询 为 Capgo 咨询中的产品工作流程和 Capgo 高级支持 为 Capgo 高级支持中的产品工作流程。