跳转至正文
教程

使用 Firebase 实现 Ionic Capacitor 推送通知:分步指南

了解如何通过 Firebase 在 Ionic Capacitor 应用中集成推送通知,并查看适用于 Android 和 iOS 平台的分步说明。

“Ionic Capacitor 结合 Firebase 实现推送通知:分步指南” Capgo 博客插图

本教程中,我们将使用 Firebase 在 Ionic Capacitor 应用中集成推送通知。如需支持 Firebase Cloud Messaging 且持续维护的 Capacitor 插件,请参阅 @capgo/capacitor-firebase-messaging。这不需要特定服务,但需要提前配置好几项内容。Firebase 是很好的选择,因为 Android 必须用到它,而且你可以轻松用它发送通知,无需使用数据库。

首先,我们创建一个启用 Capacitor 的 Ionic 应用,并指定我们的 包 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 的对话框看起来很相似,关键是要使用你的 包 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 Developer 账户。请确保你 从列表中选择 Push Notifications 功能 。

ionic-ios-push-id

本指南中介绍的 Bundle ID 应与 Capacitor 和 Firebase 中的 App ID 保持一致。

现在, 创建一个 Key 并启用 Apple 推送通知服务(APNs)。如果你已达到 Key 数量上限,可以使用现有的 Key 或证书,但流程会更复杂。

ios-developer-push-key

下载 .p8 文件后,将其上传到 Firebase。打开 云消息传递 (Cloud Messaging) 标签页,上传该文件,并填写 Key ID 和 iOS 的 Team ID 信息。

firebase-upload-ios-key

现在,运行以下命令来修改 Xcode 项目:

npx cap open ios

复制 GoogleService-Info.plist 文件(从 Firebase 下载)拖到您的 iOS 项目中。将该文件拖到 Xcode 项目的 app/app 文件夹内,并选择 需要时拷贝项目.

接下来,在 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 项目中为推送通知添加 Capability。

capacitor-xcode-capability

现在,构建你的应用并集成推送通知。

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

创建服务处理推送通知,文件位于 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) 并选择 发送测试消息。从日志中获取设备 token。

firebase-test-push

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

带 Payload 的推送消息

要测试包含附加信息的推送通知,请按照同一页面上的向导操作,填写通用信息并选择目标平台。添加 附加选项 以便随推送通知一起发送 payload。

firebase-push-payload

在 高级选项 部分,添加一个 自定义数据 键值对。例如,你可以使用键 detailsId 以及任意值。应用将使用此数据导航到指定 id 的详情页。

发送推送通知后,应用应能收到该通知,并在点击通知时显示指定 id 的详情页。

使用 Firebase API

你还可以使用 Firebase API 以编程方式发送推送通知。为此,你需要获取 服务器密钥 ,它位于 Firebase 项目设置中的 云消息传递 (Cloud Messaging) 选项卡。

下。有了服务器密钥,你可以向 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 替换为你实际的服务器密钥和设备 token。运行脚本,你的设备应该会收到带有自定义 payload 的推送通知。

搞定!你已成功使用 Firebase 在 Ionic Capacitor 应用中集成了推送通知。现在,你可以向 Android 和 iOS 平台上的用户发送推送通知了。

继续阅读 Ionic Capacitor 使用 Firebase 的推送通知:分步指南

如果你正在使用 使用 Firebase 实现 Ionic Capacitor 推送通知:分步指南 要规划迁移和企业运营,请将其与 Capgo 企业版 用于 Capgo Enterprise 中的产品工作流, Ionic Enterprise 插件替代方案 用于 Ionic Enterprise 插件替代方案的产品工作流, Capgo 替代方案 用于 Capgo 替代方案的产品工作流, Capgo 咨询 适用于 Capgo Consulting 的产品工作流,以及 Capgo 高级支持 适用于 Capgo Premium Support 的产品工作流。

为 Capacitor 应用提供 Live Updates

当 Web 层出现线上 Bug 时,通过 Capgo 发布修复,而不用等 App Store 审核好几天。用户会在后台收到更新,原生变更则仍走正常审核流程。

博客最新动态

Capgo 为你提供打造真正专业的移动应用所需的最有价值的洞察。