In this tutorial, we will integrate push notifications in an Ionic Capacitor app using Firebase. For a maintained Capacitor plugin with Firebase Cloud Messaging support, see @capgo/capacitor-firebase-messaging. 푸시 알림을 사용하려면 특정 서비스가 필요하지 않지만, 몇 가지 설정을 미리 구성해야 합니다. Firebase는 안드로이드에서 필수이기 때문에 푸시 알림을 보내기 위해 데이터베이스를 사용하지 않아도 쉽게 사용할 수 있습니다.
First, we will create an Ionic app with Capacitor enabled and specify our 패키지 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 을 변경하여 앱의 appIdnative 폴더가 이미 존재한다면, Capacitor은 폴더를 한번만 생성하고 id를 업데이트하지 않기 때문에, 모든 파일에서 id를 Capacitor으로 대체해야 합니다. 업데이트되지 않습니다.__CAPGO_KEEP_0__.config.json 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 프로젝트를 생성하거나 기존 프로젝트를 사용하세요. 새로운 프로젝트를 생성할 경우 이름과 기본 옵션을 지정하세요. 새로운 앱이 있다면,
__CAPGO_KEEP_0__은 폴더를 한번만 생성하고 id를 업데이트하지 않기 때문에, 모든 파일에서 id를 __CAPGO_KEEP_0__으로 대체해야 합니다. 앱에 Firebase를 추가하기 위해 시작하세요 앱의 대시보드에서 찾으세요. 그렇지 않으면 기어 아이콘을 클릭하고 프로젝트 설정으로 이동하세요. 프로젝트 설정 앱을 추가하세요.
iOS와 Android의 다이얼로그는 유사하며, 중요한 것은 앱의 패키지 ID를 사용하는 것입니다. 패키지 ID firebase-app-setup-ios
Android용 google-services.json 파일
- GoogleService-info.plist 파일 firebase-app-setup-ios
- __CAPGO_KEEP_0__ iOS 파일
다음으로 플랫폼을 구성하세요.
안드로이드 푸시 준비
안드로이드의 경우 폴더를 이동하세요. 다운로드 한 google-services.json 파일 파일을 android/app/ 폴더로 android-push-file 안드로이드 준비는 여기까지입니다. 이제 iOS를 구성해 보겠습니다.
이 부분은 더 복잡합니다. 먼저
android-push-file
iOS를 구성해 보겠습니다. 앱 ID를 생성하여 앱 내의 식별자 목록에 추가하세요. 애플 개발자 계정의 식별자 목록에서 Push Notifications 기능을 선택하세요. Push Notifications 기능을 선택하세요. Push Notifications 기능을 선택하세요.

APNs Bundle ID should be the same as your App ID within Capacitor and Firebase.
이제 키를 생성하고 Apple Push Notifications 서비스(APNs)를 활성화하세요. 키를 생성하고 Apple Push Notifications 서비스(APNs)를 활성화하세요. Apple Push Notifications 서비스(APNs)를 활성화하세요. __CAPGO_KEEP_0__. iOS에서 최대 키 수를 초과한 경우 기존 키 또는 인증서를 사용할 수 있지만 프로세스는 더 복잡합니다.

다운로드 받은 .p8 다운로드 받은 파일을 Firebase로 업로드하세요. Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드한 후 iOS에서 Key ID와 팀 ID의 세부 정보를 입력하세요.

이제 Xcode 프로젝트에 변경 사항을 적용하세요.
npx cap open ios
다운로드 받은 GoogleService-Info.plist 파일을 iOS 프로젝트로 복사하고 Xcode 프로젝트 내의 app/app 폴더에 파일을 끌어당겨 선택하세요. 필요한 경우 아이템을 복사하세요.
다음으로 Firebase 의존성을 위한 새로운 Pod을 추가하세요 ios/App/Podfile:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
이 명령어로 네이티브 플랫폼을 업데이트하세요:
npx cap update ios
네이티브 스위프트 code을 ios/App/App/AppDelegate.swift 에서 수정하세요 Firebase와 등록하고 올바른 토큰을 앱에 반환하세요. 마지막으로 Xcode 프로젝트에서 Push Notification Capability을 추가하세요.
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)
}
}
}
}
__CAPGO_KEEP_0__-xcode-capability

아이온 푸시 알림 통합
아이온 프로젝트에서 서비스와 새로운 페이지를 생성하세요:
Push Notification을 통합하세요.
ionic g service services/fcm
ionic g page pages/details
Push 알림을 Firebase로 Ionic 및 Capacitor에서 사용하는 방법 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 { }
Push 알림을 처리하는 서비스를 생성하여 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}`);
}
}
);
}
}
Push 알림을 호출하는 함수를 initPush() app/app.component.ts Push 알림 정보를 처리하는 페이지를:
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 Push 알림 정보를 표시하는 페이지를:
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 Push 알림을 Firebase로 Ionic 및 Capacitor에서 사용하는 방법:
<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로그에서 장치 토큰을 추가하세요.

모든 설정이 올바르게 구성되어 있다면, 장치에 푸시 알림이 표시되어야 합니다.
Payload를 포함한 Push 메시지
추가 정보를 포함한 푸시 알림을 테스트하려면, 이 페이지에서 일반 정보를 지정하고 대상 플랫폼을 선택하는 마법사를 따라하세요. 추가 추가 옵션 추가 옵션

firebase-push-payload 고급 옵션 섹션에서, Custom data 키-값 pair를 추가하세요. 예를 들어, 키 detailsId 선택한 id와 함께 상세 페이지로 이동할 수 있습니다.
푸시 알림을 보내고 나면, 앱은 푸시 알림을 받고, 알림을 탭하면 id가 지정된 상세 페이지를 표시해야 합니다.
Firebase API
Firebase API를 사용하여 프로그래밍적으로 푸시 알림을 보내실 수 있습니다. 푸시 알림을 보내려면 Firebase 프로젝트 설정에서 Cloud Messaging 탭의 Server key를 얻으셔야 합니다. Server key Cloud Messaging 서버 키를 사용하여 Firebase __CAPGO_KEEP_0__로 POST 요청을 보내고 필요한 데이터를 포함하여 푸시 알림을 보내실 수 있습니다.
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 서버 키와 기기 토큰을 실제로 대체하세요.
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 푸시 알림을 성공적으로 통합했습니다! 이제 Ionic __CAPGO_KEEP_0__ 앱에서 Firebase를 사용하여 Android와 iOS 플랫폼에서 푸시 알림을 보낼 수 있습니다. YOUR_DEVICE_TOKEN That’s it! You’ve successfully integrated push notifications in your Ionic __CAPGO_KEEP_0__ app using Firebase. Now you can send push notifications to your users on both Android and iOS platforms.
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
이미 아이온IC 푸시 알림을 사용 중이라면 Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide 이동 및 기업 운영을 계획하고 연결하려면 Capgo Enterprise 제품 워크플로우에서 Capgo Enterprise를 사용 __CAPGO_KEEP_0__ Enterprise Plugin 대체 제품 워크플로우에서 __CAPGO_KEEP_0__ Enterprise Plugin 대체를 사용 Capgo 대체 제품 워크플로우에서 Capgo 대체를 사용 Capgo 컨설팅 제품 워크플로우에서 Capgo 컨설팅을 사용 Capgo 프리미엄 지원 Capgo 프리미엄 지원 제품 워크플로우에 대한 지원