Ini tutorial ini, kami akan mengintegrasikan notifikasi push di aplikasi Capacitor Ionic 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 notifikasi tanpa menggunakan database.
Pertama, kami akan membuat aplikasi Ionic dengan Capacitor diaktifkan dan menentukan ID paket kami, yang merupakan identifikasi unik untuk aplikasi Anda. Kemudian, kami akan membangun aplikasi dan menambahkan platform native. Jika Anda sudah memiliki aplikasi, Anda dapat mengubah __CAPGO_KEEP_0__.config.json untuk mencakup ID aplikasi Anda. Namun, jika folder native Anda sudah ada, Anda perlu mengganti ID di semua file di mana ID tersebut muncul, karena __CAPGO_KEEP_0__ hanya membuat folder sekali dan__CAPGO_KEEP_0__ hanya membuat folder sekali dan
ionic start pushApp blank --type=angular --capacitor --package-id=com.appdactic.devpush
cd ./pushApp
ionic build
npx cap add ios
npx cap add android
__CAPGO_KEEP_0__ hanya membuat folder sekali dan capacitor hanya membuat folder sekali dan __CAPGO_KEEP_0__ hanya membuat folder sekali dan __CAPGO_KEEP_0__ hanya membuat folder sekali danCapacitor 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 menerima notifikasi, dan menampilkan peringatan ketika notifikasi 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 notifikasi push di luar aplikasi.
Konfigurasi Firebase
Mulailah 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 “Mulai dengan menambahkan Firebase ke aplikasi Anda” di dashboard aplikasi Anda. Jika tidak, klik ikon roda gigi dan pergi ke Pengaturan Proyek Untuk menambahkan sebuah aplikasi.
Dialog untuk iOS dan Android terlihat sama, dan hal yang penting adalah menggunakan ID paket Anda untuk aplikasi-aplikasi tersebut. firebase-app-setup-ios
google-services.json
- file untuk Android GoogleService-info.plist
- file untuk iOS Selanjutnya, atur platform-platform.
Konfigurasi platform-platform.
Persiapan Push Android
Untuk Android, pindahkan file google-services.json yang Anda download ke folder android/app/ android-push-file
Persiapan Push iOS
Bagian ini lebih rumit. Pertama-tama, buatlah ID Aplikasi untuk aplikasi Anda di dalam daftar pengenal
di akun pengembang Apple Anda. Pastikan Anda __CAPGO_KEEP_0__ __CAPGO_KEEP_1__ Pilih kemampuan Notifikasi Push dari daftar.

The ID Paket harus sama dengan ID Aplikasi Anda di Capacitor dan Firebase.
Sekarang, buatlah Kunci dan aktifkan layanan Notifikasi Push Apple (APNs) Jika Anda telah mencapai batas jumlah kunci maksimal, Anda dapat menggunakan kunci yang sudah ada atau sertifikat, tetapi prosesnya lebih rumit.ios-developer-push-key

Setelah mengunduh file .p8 upload ke Firebase. Buka tab Cloud Messaging di pengaturan proyek Firebase Anda, upload file tersebut, dan masukkan detail untuk Key ID dan ID Tim dari iOS.

Sekarang, buat perubahan pada proyek Xcode Anda dengan menjalankan:
npx cap open ios
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 Copy items if needed.
Selanjutnya, tambahkan Pod baru untuk dependensi Firebase di iOS/App/Podfile:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
Perbarui platform native dengan perintah ini:
npx cap update ios
Modifikasi native Swift code di 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)
}
}
}
}
Terakhir, 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 di 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 { }
Membuat layanan untuk mengelola pemberitahuan 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 Menangani 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 Bangun aplikasi, sinkronkan perubahan, dan terapkan 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 pemberitahuan push dengan Firebase.
ionic build
npx cap sync
untuk mencakup halaman baru dengan id dinamis:
Menyampaikan Pemberitahuan Push dengan Firebase
Ada beberapa cara untuk menyampaikan pemberitahuan 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 pemberitahuan push sasaran untuk memastikan integrasi Anda berfungsi. Di Firebase, pergi ke Pengiriman Pesan dan pilih Kirim pesan uji. Tambahkan token perangkat dari log.

Jika semuanya sudah terkonfigurasi dengan benar, Anda harus melihat pemberitahuan push di perangkat Anda.
Pemberitahuan Push dengan Payload
Untuk menguji pemberitahuan push dengan informasi tambahan, ikuti petunjuk di halaman yang sama untuk menentukan informasi umum dan memilih platform yang ingin ditargetkan. Tambahkan opsi tambahan untuk mengirimkan payload dengan pemberitahuan push Anda.

Dalam bagian opsi lanjutan Bagian, tambahkan pasangan nilai kunci. Contohnya, Anda dapat menggunakan kunci dan nilai pilihan Anda. Data ini akan digunakan di aplikasi untuk menavigasi ke halaman detail dengan id yang ditentukan. detailsId Setelah mengirimkan pemberitahuan push, aplikasi Anda harus menerima dan menampilkan halaman detail dengan id yang ditentukan ketika pemberitahuan di-klik.
Menggunakan Firebase __CAPGO_KEEP_0__
Anda juga dapat mengirimkan pemberitahuan push secara programatis menggunakan Firebase API. Untuk melakukan ini, Anda perlu mendapatkan
API Kunci Server dari pengaturan proyek Firebase Anda di bawah tab Cloud Messaging tab.
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 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.
Keep going from Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide
Selesai! Anda telah berhasil mengintegrasi notifikasi push di aplikasi Ionic __CAPGO_KEEP_0__ Anda menggunakan Firebase. Sekarang Anda dapat mengirimkan notifikasi push ke pengguna Anda di kedua platform Android dan iOS. Ionic Capacitor Pemberitahuan Push dengan Firebase: Panduan Langkah demi Langkah untuk merencanakan migrasi dan operasional bisnis, hubungkannya dengan Capgo Bisnis untuk alur kerja produk di Capgo Bisnis, Pengganti Plugin Bisnis Ionic untuk alur kerja produk di Pengganti Plugin Bisnis 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.