Lebih lanjut ke konten utama
Tutorial

Ionic Capacitor Notifikasi Push dengan Firebase: Panduan Langkah demi Langkah

Belajar bagaimana mengintegrasikan notifikasi push di aplikasi Ionic Capacitor Anda menggunakan Firebase, dengan instruksi langkah demi langkah untuk platform Android dan iOS.

Kredit artikel

Martin Donadieu

Pengarang

Valeria

Pengulas

Jordan

Pengedit

Ionic Capacitor Pemberitahuan Push dengan Firebase: Panduan Langkah demi Langkah

Dalam tutorial ini, kami akan mengintegrasikan pemberitahuan push dalam aplikasi Ionic Capacitor menggunakan Firebase. Untuk plugin yang dipertahankan Capacitor dengan dukungan Firebase Cloud Messaging, lihat @capgo/capacitor-firebase-messaging. Anda tidak memerlukan layanan tertentu untuk ini, tetapi Anda perlu mengonfigurasi beberapa hal sebelumnya. Firebase adalah pilihan yang 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 idPaket ID, yang merupakan identifikasi unik untuk aplikasi Anda. Kemudian, kita 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 aplikasi Anda Di . However, if your native folders already exist, you will need to replace the id in all files where it appears, as Capacitor only creates the folder once and tidak akan memperbarui id itu sendiriDalam capacitor.config.jsonAnda juga dapat menentukan opsi seperti memperbarui jumlah badge, memainkan suara ketika pemberitahuan datang, 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 konfigurasi notifikasi 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 “Mulai dengan menambahkan Firebase ke aplikasi Anda” di dashboard aplikasi Anda. Jika tidak, klik ikon gear dan pergi ke pengaturan proyek untuk menambahkan aplikasi.

Dialog untuk kedua iOS dan Android terlihat sama, dan hal yang penting adalah menggunakan ID paket Anda untuk aplikasi.

firebase-app-setup-ios

Setelah langkah awal, download file-file berikut:

  • google-services.json file untuk Android
  • GoogleService-info.plist file untuk iOS

Selanjutnya, konfigurasi platform.

Persiapan Push Android

Untuk Android, pindahkan google-services.json file yang Anda download ke folder android/app/ Folder.

File Android Push

Itu sudah selesai untuk Android. Sekarang mari kita atur iOS.

Pengaturan 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 memilih kemampuan Push Notification dari daftar. ionic-ios-push-id

ionic-ios-push-id

ID Paket ID Paket harus sama dengan ID aplikasi Anda di Capacitor dan Firebase.

Sekarang, buatlah Kunci mengaktifkan Jasa Pemberitahuan Push Apple (APNs). If you have reached the maximum number of keys, you can use an existing key or a certificate instead, but the process is more complicated.

ios-developer-push-key

Setelah mengunduh file. .p8 file, unggahnya ke Firebase. Buka Pengiriman Pesan Buka tab pengaturan Firebase project, unggah file, dan masukkan detail untuk Key ID dan ID Tim dari iOS.

firebase-upload-ios-key

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 ke dalam proyek Xcode di dalam folder app/app, dan pilih Salin jika diperlukan.

Selanjutnya, tambahkan Pod baru untuk dependensi Firebase di dalam 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 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.

capacitor-kemampuan-xcode

Sekarang, bangun aplikasi Anda dan integrasikan notifikasi push.

Integrasi Notifikasi Push Ionik

Buat layanan dan halaman baru dalam proyek Ionik 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 { }

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}`);
        }
      }
    );
  }
}

Tunggu panggilan initPush() fungsi tersebut Aplikasi/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();
    });
  }
}

Pahami informasi di halaman detail di halaman/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();
  }

}

Tampilkan detail di halaman/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>

Bangun aplikasi, sinkronkan perubahan, dan terapkan ke perangkat Anda.

ionic build
npx cap sync

Sekarang, Anda dapat mengirimkan notifikasi push dengan Firebase.

Mengirimkan Notifikasi Push dengan Firebase

Ada beberapa cara untuk mengirimkan 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. Di Firebase, pergi ke Pengiriman Pesan Pilih dan pilih Kirim pesan uji. Tambahkan token perangkat dari log.

firebase-test-push

Jika semua sudah terkonfigurasi dengan benar, Anda harus melihat notifikasi push di perangkat Anda.

Pesan Push dengan Payload

Untuk menguji notifikasi push dengan informasi tambahan, ikuti petunjuk di halaman yang sama untuk menentukan informasi umum dan memilih platform yang ingin ditargetkan. Tambahkan opsi tambahan untuk mengirim payload dengan notifikasi push Anda.

firebase-push-payload

Dalam Opsi Lanjutan Bagian, tambahkan sebuah Data kustom pasang pasang nilai kunci. Misalnya, Anda dapat menggunakan kunci detailsId dan nilai pilihan Anda. Data ini akan digunakan di aplikasi untuk menavigasi ke halaman detail dengan id yang ditentukan.

Setelah mengirimkan notifikasi push, aplikasi Anda harus menerima dan menampilkan halaman detail dengan id yang ditentukan ketika notifikasi diklik.

Menggunakan Firebase API

Anda juga dapat mengirimkan notifikasi push secara programatis menggunakan Firebase API. Untuk melakukan ini, Anda perlu mendapatkan Kunci Server dari pengaturan proyek Firebase Anda di bawah tab Pengiriman Pesan tab.

With the server key, you can send a POST request to the Firebase API with the required payload. Here’s an example using Node.js and the 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: Page/area: Capgo marketing website. Role: Short UI label or navigation item. Seen in: page trust.astro. Message key `and` (And).

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.

Teruskan dari Ionic Capacitor Notifikasi Push dengan Firebase: Panduan Langkah demi Langkah

Jika Anda menggunakan Ionic Capacitor Pemberitahuan Push dengan Ionic dan Firebase: Panduan Langkah demi Langkah Ionic __CAPGO_KEEP_0__ Notifikasi Push dengan Firebase: Panduan Langkah demi Langkah Capgo Enterprise untuk alur kerja produk di Capgo Enterprise, Alternatif Plugin Enterprise Ionic untuk alur kerja produk di Ionic Enterprise Plugin Alternatives, Alternatif Capgo untuk alur kerja produk di Alternatif Capgo Capgo Konsultasi untuk alur kerja produk di Capgo Konsultasi, dan Capgo Layanan Premium untuk alur kerja produk di Capgo Layanan Premium.

Pembaruan Langsung untuk Capacitor apps

Ketika bug layer web masih aktif, kirimkan perbaikan melalui Capgo daripada menunggu hari-hari untuk persetujuan toko aplikasi. Pengguna mendapatkan pembaruan di latar belakang sementara perubahan native tetap dalam jalur review normal.

Terbaru dari Blog kami

Capgo memberikan Anda wawasan terbaik yang Anda butuhkan untuk membuat aplikasi mobile profesional yang sebenarnya.