Dalam tutorial ini, kami akan mengintegrasikan pemberitahuan push di aplikasi Ionic Capacitor menggunakan Firebase. Untuk plugin yang dipelihara Capacitor dengan dukungan Firebase Cloud Messaging, lihat @capgo/capacitor-firebase-messaging. Anda tidak memerlukan layanan khusus untuk ini, tetapi Anda perlu mengonfigurasi beberapa hal sebelumnya. Firebase adalah pilihan yang sangat baik karena diperlukan untuk Android, dan Anda dapat dengan mudah menggunakan itu untuk mengirimkan pemberitahuan tanpa menggunakan database.
Pertama, kami akan membuat aplikasi Ionic dengan Capacitor diaktifkan dan menentukan package id, yang merupakan identifier unik untuk aplikasi Anda. Kemudian, kami akan membangun aplikasi dan menambahkan platform native.
ionic start pushApp blank --type=angular --capacitor --package-id=com.appdactic.devpush
cd ./pushApp
ionic build
npx cap add ios
npx cap add android
Jika Anda sudah memiliki aplikasi, Anda dapat mengubah capacitor.config.json untuk mencakup appId. Namun, jika folder native Anda sudah ada, Anda perlu mengganti id di semua file di mana id tersebut muncul, karena Capacitor hanya membuat folder sekali dan tidak akan memperbarui id itu sendiri. Di capacitor.config.json, Anda juga dapat menentukan opsi seperti memperbarui jumlah badge, memainkan suara ketika push, dan menampilkan peringatan ketika pemberitahuan datang.
{
"appId": "com.appdactic.devpush",
"appName": "pushApp",
"bundledWebRuntime": false,
"npmClient": "npm",
"webDir": "www",
"plugins": {
"SplashScreen": {
"launchShowDuration": 0
},
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
},
"cordova": {}
}
Sekarang, mari kita atur pemberitahuan push di luar aplikasi.
Konfigurasi Firebase
Mulai dengan membuat proyek Firebase baru atau menggunakan yang sudah ada. Berikan nama dan opsi default untuk proyek baru.
Jika Anda memiliki aplikasi baru, Anda harus melihat “Get started by adding Firebase to your app” untuk menambahkan Firebase ke aplikasi Anda Pengaturan Proyek Untuk menambahkan aplikasi.
Dialog untuk iOS dan Android terlihat sama, dan hal yang penting adalah menggunakan __CAPGO_KEEP_0__ untuk aplikasi.
Setelah langkah awal, unduh file-file berikut:
- google-services.json File untuk Android
- GoogleService-info.plist File untuk iOS
Selanjutnya, atur platform.
Persiapan Push Android
Untuk Android, pindahkan google-services.json file yang Anda download ke folder android/app/ .
Itu saja untuk Android. Sekarang mari kita atur iOS.
Persiapan Push iOS
Bagian ini lebih rumit. Pertama, buat ID Aplikasi untuk aplikasi Anda di dalam daftar pengenal akun Pengembang Apple Anda. Pastikan Anda Pilih kemampuan Push Notifications dari daftar.

The ID Paket harus sama dengan ID Aplikasi Anda di __CAPGO_KEEP_0__ dan Firebase. should be the same as your App ID within Capacitor and Firebase.
buatlah sebuah Kunci dan aktifkan layanan Push Notifications Apple (APNs) . Jika Anda telah mencapai batas maksimal kunci, Anda dapat menggunakan kunci yang sudah ada atau sertifikat, tetapi prosesnya lebih rumit. ios-developer-push-key__CAPGO_KEEP_0__

After mengunduh file .p8, unggahlah ke Firebase. Buka tab Cloud Messaging di pengaturan proyek Firebase Anda, unggah file tersebut, dan masukkan detail untuk Key ID dan ID Tim dari iOS. firebase-upload-ios-key Sekarang, buat perubahan pada proyek Xcode Anda dengan menjalankan perintah: Salin file GoogleService-Info.plist yang Anda download dari Firebase ke proyek iOS Anda. Drag file tersebut ke dalam proyek Xcode di dalam folder app/app, dan pilih Salin item jika diperlukan

Tambahkan Pod baru untuk dependensi Firebase di dalam proyek Anda.
npx cap open ios
Jalankan perintah berikut untuk menginstal Pod Firebase: Jalankan perintah berikut untuk menginstal Pod Firebase: Jalankan perintah berikut untuk menginstal Pod Firebase: Jalankan perintah berikut untuk menginstal Pod Firebase:.
Jalankan perintah berikut untuk menginstal Pod Firebase: ios/Podfile:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
Jalankan perintah ini untuk memperbarui platform native:
npx cap update ios
Modifikasi Swift native code dalam ios/App/App/AppDelegate.swift untuk mendaftarkan dengan Firebase dan mengembalikan token yang benar ke aplikasi Anda.
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)
}
}
}
}
Akhirnya, tambahkan Kemampuan untuk Notifikasi Push dalam proyek Xcode Anda.

Sekarang, bangun aplikasi Anda dan integrasikan notifikasi push.
Integrasi Notifikasi Push Ionic
Buat layanan dan halaman baru dalam proyek Ionic Anda:
ionic g service services/fcm
ionic g page pages/details
Perbarui routing dalam app/app-routing.module.ts untuk mencakup halaman baru dengan id dinamis:
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 { }
Buat layanan untuk mengelola notifikasi push di 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}`);
}
}
);
}
}
Panggil fungsi di initPush() app/app.component.ts Tangani informasi pada halaman detail di:
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 Tampilkan detail di:
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 Buat aplikasi, sinkronkan perubahan, dan deploy ke perangkat Anda.:
<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>
Sekarang, Anda dapat mengirim notifikasi push dengan Firebase.
ionic build
npx cap sync
__CAPGO_KEEP_0__
Menyebarkan Notifikasi Push dengan Firebase
Ada beberapa cara untuk menyebarkan notifikasi push dengan Firebase.
Pengujian Perangkat Khusus
Setelah mengunduh aplikasi ke perangkat, Anda dapat memeriksa log konsol untuk melihat token setelah registrasi. Gunakan token ini untuk mengirimkan tes push yang sasaran untuk memastikan integrasi Anda berfungsi. Dalam Firebase, pergi ke Pengiriman Pesan dan pilihKirim pesan tes

firebase-test-push
Jika semuanya sudah terkonfigurasi dengan benar, Anda harus melihat notifikasi push di perangkat Anda.
Notifikasi Push dengan Payload Data Tambahan opsi tambahan untuk mengirimkan payload dengan pemberitahuan push Anda.

Di bagian opsi lanjutan tambahkan pasangan nilai kunci- data kustom pasangan nilai kunci- detailsId data kustom
Contoh, Anda dapat menggunakan kunci
Using Firebase API
You can also send push notifications programmatically using the Firebase API. To do this, you need to obtain the Kunci server dari pengaturan proyek Firebase Anda di bawah tab Cloud Messaging .
Dengan kunci server, Anda dapat mengirimkan permintaan POST ke Firebase API dengan payload yang diperlukan. Berikut adalah contoh menggunakan Node.js dan request library:
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);
}
});
Ganti YOUR_SERVER_KEY dan YOUR_DEVICE_TOKEN dengan kunci server yang sebenarnya dan token perangkat. Jalankan skrip, dan perangkat Anda seharusnya menerima notifikasi push dengan payload kustom.
Itu saja! Anda telah berhasil mengintegrasikan notifikasi push di aplikasi Ionic Capacitor Anda menggunakan Firebase. Sekarang Anda dapat mengirimkan notifikasi push ke pengguna Anda di kedua platform Android dan iOS.
Lanjutkan dari Ionic Capacitor Push Notifications dengan Firebase: Panduan Langkah demi Langkah
Jika Anda menggunakan Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide untuk merencanakan migrasi dan operasional perusahaan, hubungkannya dengan Capgo Perusahaan untuk alur kerja produk di Capgo Perusahaan, Alternatif Plugin Perusahaan Ionic untuk alur kerja produk di Alternatif Plugin Perusahaan Ionic, Capgo Alternatif untuk alur kerja produk di Capgo Alternatif, Capgo Konsultasi untuk alur kerja produk di Capgo Konsultasi, dan Capgo Layanan Premium untuk alur kerja produk di Capgo Layanan Premium.