In 이 튜토리얼에서, 우리는 Ionic Capacitor 앱에 푸시 알림을 통합할 것입니다. Firebase와 함께 Firebase Cloud Messaging 지원을 갖춘 유지 관리 Capacitor 플러그인을 보려면 @capgo/capacitor-firebase-messaging. 이 작업을 위해 특정 서비스가 필요하지 않지만, 몇 가지 설정을 미리 구성해야 합니다. Firebase는 Android에서 필수적이기 때문에 안정적인 선택이며, 데이터베이스를 사용하지 않고도 알림을 쉽게 전송할 수 있습니다.
첫 번째로, 우리는 Ionic 앱을 Capacitor가 활성화된 상태로 만들고, package 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 파일을 변경하여 앱 ID를 포함할 수 있습니다. 그러나 네이티브 폴더가 이미 존재한다면, __CAPGO_KEEP_0__. 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에서 옵션을 지정할 수 있습니다. 예를 들어, 배지 수를 업데이트 하거나 푸시 시 소리를 재생하거나, 알림이 도착했을 때 경고를 표시할 수 있습니다. 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": {}
}
먼저
새로운 파이어베이스 프로젝트를 만들거나 기존 프로젝트를 사용하세요.
새로운 프로젝트의 이름과 기본 옵션을 지정하세요. 새로운 앱이 있다면 or using an existing one. Provide a name and default options for a new project.
앱의 대시보드에서 “Get started by adding Firebase to your app” ‘앱에 파이어베이스를 추가하여 시작하세요.’ 프로젝트 설정 앱을 추가하려면.
iOS와 Android의 대화 상자는 유사하며, 중요한 것은 앱에 사용하는 package id 입니다.
초기 단계 이후에 다운로드해야 하는 파일은 다음과 같습니다.
- Android용 google-services.json
- iOS용 GoogleService-info.plist
파일입니다. 다음으로 플랫폼을 구성하세요.
Android Push Preparation
Android에서 사용하려면 __CAPGO_KEEP_0__ __CAPGO_KEEP_0__ 다운로드한 android/app/
Android 설정은 끝났습니다. 이제 iOS를 설정해 보겠습니다.
iOS Push Preparation
이 부분은 더 복잡합니다. 첫 번째로 Apple Developer 계정의 식별자 목록 내에서 앱 ID를 생성하세요. 앱 ID를 생성한 후 __CAPGO_PUSH_NOTIFICATIONS_CAPABILITY__ __CAPGO_LIST__

__CAPGO_THE__ __CAPGO_BUNDLE_ID__ should be the same as your App ID within Capacitor and Firebase.
__CAPGO_NOW__ __CAPGO_CREATE_A_KEY__ __CAPGO_ENABLE_THE_APPLE_PUSH_NOTIFICATIONS_SERVICE__ __CAPGO_IF_YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_KEYS____CAPGO_YOU_CAN_USE_AN_EXISTING_KEY_OR_A_CERTIFICATE_INSTEAD__

After 다운로드 후 Firebase에 업로드하세요. Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드하고 Key ID와 iOS의 Team ID의 세부 정보를 입력하세요. .p8 파일을 Firebase에 업로드하고 Cloud Messaging 탭에서 Key ID와 iOS의 Team ID의 세부 정보를 입력하세요. firebase-upload-ios-key Xcode 프로젝트를 수정하려면 다음 명령어를 실행하세요:

Next, Firebase 의존성을 위한 새로운 Pod를 추가하세요.
npx cap open ios
firebase-pod-add Now, make changes to your Xcode project by running: Copy the GoogleService-Info.plist file you downloaded from Firebase into your iOS project. Drag the file into the Xcode project inside the app/app folder, and select Copy items if needed Next, add a new Pod for the Firebase dependency in the.
firebase-pod-add ios/App/Podfile:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Messaging'
end
iOS 플랫폼을 업데이트하려면 다음 명령어를 사용하세요.
npx cap update ios
iOS Swift code을 code에 수정하세요. ios/App/App/AppDelegate.swift 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 알림을 통합하세요.
Ionic Push 알림 통합
Ionic 프로젝트에서 서비스와 새로운 페이지를 생성하세요.
ionic g service services/fcm
ionic g page pages/details
Update the routing in 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 { }
푸시 알림을 처리하는 서비스를 만들기 위해: 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}`);
}
}
);
}
}
함수 호출하기: initPush() 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>
현재, Firebase를 사용하여 푸시 알림을 보낼 수 있습니다.
ionic build
npx cap sync
services/fcm.service.ts
Firebase Push 알림 보내기
Firebase Push 알림을 보내기 위한 여러 가지 방법이 있습니다.
특정 기기 테스트
앱을 기기에 배포한 후, 등록 후 토큰을 확인하기 위해 콘솔 로그를 확인할 수 있습니다. 이 토큰을 사용하여 대상 테스트 푸시를 보내어 통합이 작동하는지 확인합니다. Firebase에서 Cloud Messaging 으로 이동하여 테스트 메시지 전송을 선택합니다. 로그에서 기기 토큰을 추가합니다.

모든 설정이 올바르게 구성되어 있다면, 기기에 푸시 알림을 볼 수 있습니다.
추가 정보를 포함한 푸시 알림 테스트
추가 정보를 지정하고 대상 플랫폼을 선택하기 위해 동일한 페이지의 마법사를 따라서 푸시 알림을 테스트할 수 있습니다. 추가 옵션 푸시 알림과 함께 데이터를 전송하려면.

Firebase 고급 옵션 섹션에서 Custom data 키-값 pair를 추가하십시오. 예를 들어, 키 detailsId 앱에서 id와 함께 세부 정보 페이지로 이동할 수 있도록 사용됩니다.
푸시 알림을 전송한 후, 앱은 푸시 알림을 받고 id와 함께 세부 정보 페이지를 표시해야 합니다.
Using Firebase API
Firebase API를 사용하여 푸시 알림을 보내는 방법입니다. Firebase API를 사용하여 푸시 알림을 보내려면, Firebase API를 사용하여 푸시 알림을 보내는 방법입니다. 서버 키 Firebase 프로젝트 설정에서 Cloud Messaging 탭 아래에서 찾을 수 있습니다.
서버 키를 사용하여 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를 사용하는 단계별 안내서: 계속 진행하세요.
Firebase를 사용하는 경우 아이온틱 Capacitor 푸시 알림을 Firebase와 함께 사용하는 방법: 단계별 가이드 이동 및 기업 운영을 계획하고 연결하려면 Capgo 기업 제품 워크플로우를 위한 Capgo 기업 아이온틱 기업 플러그인 대안 제품 워크플로우를 위한 아이온틱 기업 플러그인 대안 Capgo 대안 제품 워크플로우를 위한 Capgo 대안 Capgo 컨설팅 제품 워크플로우를 위한 Capgo 컨설팅, Capgo 프리미엄 지원 제품 워크플로우를 위한 Capgo 프리미엄 지원.