메인 콘텐츠로 바로가기
Tutorial

Ionic Capacitor 푸시 알림을 Firebase로 통합하는 단계별 안내

Ionic Capacitor 앱에 푸시 알림을 통합하는 방법을 배워보세요. Firebase를 사용하여 Android 및 iOS 플랫폼의 단계별 지침을 따라 푸시 알림을 통합하세요.

Martin Donadieu

Martin Donadieu

콘텐츠 마케터

Ionic Capacitor 푸시 알림을 Firebase로 통합하는 단계별 안내

이 튜토리얼에서는 Ionic Capacitor 앱에 Firebase를 사용하여 푸시 알림을 통합하는 방법을 설명합니다. 이 작업을 수행하려면 특정 서비스가 필요하지 않지만, 여러 가지 설정을 미리 구성해야 합니다. Firebase는 Android에서 필수적으로 사용해야 하는 서비스이므로, 이 서비스를 사용하여 푸시 알림을 보내기 위해 데이터베이스를 사용하지 않아도 됩니다.

먼저 Capacitor를 활성화한 Ionic 앱을 생성하고, 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 에서 앱 아이디를 포함할 수 있습니다. 그러나 네이티브 폴더가 이미 존재한다면, __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 won’t update the id itself__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 Configuration

시작하기 위해 새로운 Firebase 프로젝트를 만들거나 기존 프로젝트를 사용하세요. 새로운 프로젝트의 이름과 기본 옵션을 제공하세요. 새로운 앱이 있으면

If you have a new app, you should see 앱의 대시보드에서 "Firebase를 앱에 추가하여 시작하세요."라고 표시되어야 합니다. 그렇지 않으면 기어 아이콘을 클릭하고 프로젝트 설정으로 이동하여 앱을 추가하세요. iOS와 Android용 대화 상자는 모두 유사하며, 중요한 것은 앱의 package id

를 사용하는 것입니다. firebase-app-setup-ios firebase-app-setup-android

firebase-app-setup-web

초기 단계 이후에 다음 파일을 다운로드하세요:

  • __CAPGO_KEEP_0__ 안드로이드용 파일
  • __CAPGO_KEEP_0__ iOS용 파일

다음으로 플랫폼을 구성하세요.

안드로이드 푸시 준비

안드로이드의 경우 다운로드한 __CAPGO_KEEP_0__ 파일을 __CAPGO_KEEP_0__ 폴더로 이동합니다.

안드로이드 푸시 파일

안드로이드 설정이 끝났습니다. 이제 iOS를 설정해 보겠습니다.

iOS 푸시 준비

이 부분은 더 복잡합니다. 먼저 애플 개발자 계정의 식별자 목록에서 앱에 대한 App ID를 생성하세요. Push Notifications 기능을 목록에서 선택하세요. ionic-ios-push-id Bundle ID는 __CAPGO_KEEP_0__와 Firebase와 동일해야 합니다.

Bundle ID

iOS 설정이 끝났습니다. 이제 앱을 테스트해 보겠습니다. 이제 앱을 테스트해 보겠습니다. should be the same as your App ID within Capacitor and Firebase.

Now, create a Key and enable the Apple Push Notifications service (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. Key를 생성하고 Apple Push Notifications 서비스 (APNs)를 활성화하세요. 최대 키 수를 초과한 경우 기존 키 또는 인증서를 사용할 수 있지만 프로세스는 더 복잡합니다. ios-developer-push-key APNs 키를 다운로드한 후 Firebase에 업로드하세요. Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드한 후 Key ID와 Team ID의 세부 정보를 입력하세요.firebase-upload-ios-key

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

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

APNs 키를 다운로드한 후 Firebase에 업로드하세요. Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드한 후 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와 등록하고 올바른 토큰을 앱에 반환하세요.

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 Notifications Capability을 추가하세요.

capacitor-xcode-capability

앱을 빌드하고 푸시 알림을 통합하세요.

아이오닉 푸시 알림 통합

아이오닉 프로젝트에서 서비스와 새로운 페이지를 생성하세요.

ionic g service services/fcm
ionic g page pages/details

routing을 업데이트 하세요. 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() function을 호출하세요. 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();
    });
  }
}

Handle the information on the details page in __CAPGO_KEEP_0__:

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

}

페이지의 세부 정보를 표시합니다. __CAPGO_KEEP_0__:

<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 에서 선택하세요. 테스트 메시지를 전송하세요. 로그에서 디바이스 토큰을 추가하세요.

firebase-test-push

설정이 올바르게 설정되어 있다면, 디바이스에서 푸시 알림을 볼 수 있어야 합니다.

Payload와 함께 푸시 메시지

추가 정보와 플랫폼을 선택하여 푸시 알림을 테스트하려면, 같은 페이지의 마법사를 따라하세요. 추가 옵션 푸시 알림과 함께 Payload를 전송하려면

firebase-push-payload

고급 옵션 섹션에서 추가 advanced options 사용자 정의 데이터 키-값 pair입니다. 예를 들어, 키를 "__CAPGO_KEEP_0__"로, 값은 "__CAPGO_KEEP_0__"로 지정할 수 있습니다. 이 데이터는 앱 내에서 id가 지정된 상세 페이지로 이동할 때 사용됩니다. detailsId 푸시 알림을 보내고 나면, 앱은 푸시 알림을 탭했을 때 id가 지정된 상세 페이지를 표시해야 합니다.

파이어베이스 __CAPGO_KEEP_0__를 사용하여

푸시 알림을 프로그래밍적으로 보내려면 파이어베이스 API를 사용할 수 있습니다. 이 작업을 수행하려면 파이어베이스 프로젝트 설정에서

You can also send push notifications programmatically using the Firebase API. To do this, you need to obtain the 클라우드 메시징 서버 키를 사용하여 파이어베이스 __CAPGO_KEEP_0__로 POST 요청을 보내고 필요한 데이터를 전송할 수 있습니다. 예를 들어, Node.js와 라이브러리를 사용하여 라이브러리:

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_KEYYOUR_DEVICE_TOKEN 실제 서버 키와 장치 토큰으로 대체하여 스크립트를 실행하면, 장치에 커스텀 페이로드를 포함한 푸시 알림이 전송됩니다.

그의 그것! Ionic Capacitor 앱에서 Firebase를 사용하여 푸시 알림을 성공적으로 통합했습니다. 이제 Android 및 iOS 플랫폼에서 사용자에게 푸시 알림을 전송할 수 있습니다.

Capacitor 앱에 대한 실시간 업데이트

Capgo을 사용하여 웹-layer 버그가 활성화된 경우, 앱 스토어 승인까지 며칠 기다리지 않고修정을 배포하세요. 사용자는 배경에서 업데이트를 받으면서 네이티브 변경은 일반적인 검토 경로를 유지합니다.

시작하기

블로그에서 최신 뉴스

Capgo은 전문적인 모바일 앱을 만들기 위해 필요한 최고의洞察력을 제공합니다.