이 튜토리얼에서는 아이오닉 Capacitor 앱에 푸시 알림을 Firebase와 함께 통합하는 방법을 설명합니다. Firebase Cloud Messaging을 지원하는 유지 관리되는 Capacitor 플러그인을 보려면 @capgo/capacitor-firebase-messaging이러한 서비스가 필요하지 않지만, 푸시 알림을 통합하기 전에 여러 가지 설정을 구성해야 합니다. Firebase는 Android에서 필수적이기 때문에 Android에서 푸시 알림을 보내는 데 사용할 수 있습니다. 또한 데이터베이스를 사용하지 않고 푸시 알림을 보내는 데 사용할 수 있습니다.
처음에, 우리는 Capacitor를 활성화하고 패키지 ID를 지정하여 Ionic 앱을 만들 것입니다. 패키지 ID패키지 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
이미 앱이 있다면, __CAPGO_KEEP_0__.config.json을 변경하여 앱 ID를 포함할 수 있습니다. 그러나 네이티브 폴더가 이미 존재한다면, __CAPGO_KEEP_0__는 폴더를 한번만 생성하고 ID 자체를 업데이트하지 않기 때문에 모든 파일에서 ID를 교체해야 합니다. capacitor.config.json 앱 ID __CAPGO_KEEP_0__.config.json. 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 __CAPGO_KEEP_0__.config.json앱 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": {}
}
이제 앱 외부에서 푸시 알림을 구성해 보겠습니다.
파이어베이스 구성
먼저 새로운 파이어베이스 프로젝트를 생성하거나 기존 프로젝트를 사용하세요. 새로운 프로젝트의 경우 이름과 기본 옵션을 제공하세요.
새로운 앱이 있다면 “Get started by adding Firebase to your app” 앱의 대시보드에서 "앱에 파이어베이스를 추가하여 시작하세요."라고 표시되어야 합니다. 아니면 기어 아이콘을 클릭하고 프로젝트 설정으로 이동하여 앱을 추가하세요. iOS와 Android의 대화 상자는 모두 유사하며, 중요한 것은 패키지 ID를 사용하는 것입니다.
프로젝트 설정 앱을 추가 애플리케이션에 대해.
초기 단계를 마친 후, 다음 파일을 다운로드하세요:
- google-services.json 안드로이드용 파일
- GoogleService-info.plist iOS용 파일
다음으로 플랫폼을 구성하세요.
안드로이드 푸시 준비
안드로이드의 경우, 다운로드한 파일을 이동하세요. google-services.json 안드로이드/앱/ 폴더.
안드로이드 설정은 여기까지입니다. 이제 iOS를 설정해 보겠습니다.
iOS 푸시 준비
이 부분은 더 복잡합니다. 먼저 애플 개발자 계정의 식별자 목록에서 앱 ID를 생성하세요. 푸시 알림 기능을 목록에서 선택하세요. ionic-ios-push-id The

이제 푸시 알림을 사용할 수 있습니다. Bundle ID Capacitor의 App ID와 동일해야 합니다.
현재 Key를 생성하세요. 그리고 Apple Push Notifications 서비스 (APNs)를 활성화하세요. 키의 최대 수를 초과한 경우 기존 키 또는 인증서를 사용할 수 있지만 프로세스는 더 복잡합니다.ios-developer-push-key

Capacitor Cloud Messaging을 열어보세요. Cloud Messaging Cloud Messaging Firebase 프로젝트 설정에서 탭을 클릭하고 파일을 업로드하고 Key ID와 Team ID의 세부 정보를 입력하세요.

이제 Xcode 프로젝트를 변경하기 위해 다음 명령어를 실행하세요.
npx cap open ios
다운로드 한 Firebase 파일의 GoogleService-Info.plist 파일을 iOS 프로젝트에 복사하고 Xcode 프로젝트 내의 app/app 폴더에 파일을 끌어다 놓고 Copy items if needed.
Firebase 의존성을 위한 새로운 Pod을 추가하세요. 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 Firebase와 함께 등록하고 앱에 올바른 토큰을 반환하세요.
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 프로젝트 내 Push 알림 기능을 활성화하세요.

앱을 빌드하고 Push 알림을 통합하세요.
아이온 Push 알림 통합
아이온 프로젝트에서 서비스와 새로운 페이지를 생성하세요:
ionic g service services/fcm
ionic g page pages/details
app/app-routing.module.ts에서 라우팅을 업데이트하여 새로운 페이지를 동적 아이디로 포함하세요: Push 알림을 처리하는 서비스를 services/fcm.service.ts에서 생성하세요. Push 알림을 처리하는 서비스를 호출하세요.
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 { }
__CAPGO_KEEP_0__ __CAPGO_KEEP_0__:
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}`);
}
}
);
}
}
__CAPGO_KEEP_0__ initPush() Ionic Capacitor Push 알림 Firebase 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>
앱을 빌드하고 변경 사항을 동기화하고 장치에 배포하세요.
ionic build
npx cap sync
이제 Firebase를 사용하여 푸시 알림을 보낼 수 있습니다.
Firebase를 사용하여 푸시 알림을 보내기
Firebase를 사용하여 푸시 알림을 보내기에는 여러 가지 방법이 있습니다.
특정 장치 테스트
장치에 앱을 배포한 후, 등록 후 토큰을 확인하기 위해 콘솔 로그를 확인하세요. 이 토큰을 사용하여 대상 테스트 푸시를 보내어 통합이 작동하는지 확인하세요. Firebase에서 Cloud Messaging 그리고 선택 테스트 메시지를 보내세요. 로그에서 디바이스 토큰을 추가하세요.

설정이 올바르게 설정되어 있다면 디바이스에서 푸시 알림을 볼 수 있습니다.
Payload를 포함한 푸시 메시지
추가 정보를 지정하고 대상 플랫폼을 선택하여 푸시 알림을 테스트하려면 같은 페이지의 마법사에 따라 진행하세요. 추가 추가 옵션 푸시 알림과 함께 데이터를 전송하려면

푸시 알림을 테스트하려면 고급 설정 섹션, 추가하여 사용자 정의 데이터 키-값 pair를 추가합니다. 예를 들어, 키 detailsId 및 사용자 지정한 값이 있습니다. 이 데이터는 앱에서 id를 지정한 세부 정보 페이지로 이동하는 데 사용됩니다.
푸시 알림을 보낸 후, 앱은 푸시 알림을 받고 id를 지정한 세부 정보 페이지를 표시할 때 알림을 탭할 때 표시해야 합니다.
Firebase API를 사용하여
또한 Firebase API를 사용하여 푸시 알림을 프로그래밍 방식으로 보내실 수 있습니다. 이 작업을 수행하려면 Firebase 프로젝트 설정에서 Cloud Messaging 탭의 Server key를 얻어야 합니다. 서버 키 Firebase 프로젝트 설정의 Cloud Messaging 탭에서 찾을 수 있습니다. Cloudflare Capacitor
서버 키를 사용하여 Firebase API로 POST 요청을 보내고 필요한 데이터를 전송할 수 있습니다. 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 서버 키와 기기 토큰을 실제로 대체하여 스크립트를 실행하면 기기에서 커스텀 데이터를 포함한 푸시 알림을 받을 수 있습니다.
그것이 다입니다! Ionic Capacitor 앱에서 Firebase를 사용하여 푸시 알림을 성공적으로 통합했습니다. 이제 Android 및 iOS 플랫폼에서 사용자에게 푸시 알림을 보내실 수 있습니다.
Ionic Capacitor 푸시 알림을 Firebase와 함께 사용하는 단계별 안내서
Ionic __CAPGO_KEEP_0__ 푸시 알림을 Firebase와 함께 사용하는 단계별 안내서를 사용하는 경우 이동 및 기업 운영을 계획하고 Enterprise Operations을 연결하려면 Capacitor Enterprise와 연결하세요. Enterprise Procurement Visual Signature Capgo Enterprise에서 제품 워크플로우 Capgo Enterprise 아이오닉 엔터프라이즈 플러그인 대체 아이오닉 엔터프라이즈 플러그인 대체를 위한 제품 워크플로우 Capgo 대체 Capgo 대체를 위한 제품 워크플로우 Capgo 컨설팅 Capgo 컨설팅을 위한 제품 워크플로우, 그리고 Capgo 프리미엄 지원 Capgo 프리미엄 지원을 위한 제품 워크플로우.