본문으로 바로가기
튜토리얼

아이온틱 Capacitor 푸시 알림을 Firebase로 통합하는 단계별 안내

아이온틱 Capacitor 앱에 푸시 알림을 통합하는 방법을 배워보세요. Firebase를 사용하여 Android와 iOS 플랫폼 모두에 대한 단계별 지침을 따라보세요.

마틴 도나디유

마틴 도나디유

콘텐츠 마케터

아이온틱 Capacitor 푸시 알림을 Firebase로 통합하는 단계별 안내

In 이 튜토리얼에서, 우리는 Ionic Capacitor 앱에 푸시 알림을 통합할 것입니다. 이 작업을 위해 특정 서비스가 필요하지 않지만, 몇 가지 설정을 미리 구성해야 합니다. Firebase는 안드로이드에서 필수이기 때문에 훌륭한 선택이며, 데이터베이스를 사용하지 않고도 알림을 쉽게 보내는 데 사용할 수 있습니다.

첫 번째로, 우리는 Ionic 앱을 Capacitor가 활성화된 상태로 생성하고, 패키지 ID를 지정할 것입니다. 패키지 ID는 앱의 고유 식별자입니다. 그런 다음, 앱을 빌드하고 네이티브 플랫폼을 추가할 것입니다. 이미 앱이 있는 경우, __CAPGO_KEEP_0__.config.json을 변경하여 앱 ID를 포함할 수 있습니다. 그러나 네이티브 폴더가 이미 존재하는 경우, 폴더를 생성하는 __CAPGO_KEEP_0__만 폴더를 생성하고, 폴더 내의 모든 파일에서 ID를 교체해야 합니다. __CAPGO_KEEP_0__는 ID 자체를 업데이트하지 않기 때문입니다.In

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__ capacitor __CAPGO_KEEP_0__ __CAPGO_KEEP_0__Capacitor __CAPGO_KEEP_0____CAPGO_KEEP_0__ capacitor.config.json__CAPGO_KEEP_0__.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 설정 먼저

새로운 Firebase 프로젝트를 만들거나 기존 프로젝트를 사용하세요. 새로운 프로젝트를 만들면 이름과 기본 옵션을 지정하세요. 새로운 앱이 있다면 “Firebase를 앱에 추가하여 시작하세요.” 앱의 대시보드에 표시됩니다. 그렇지 않다면 기어 아이콘을 클릭하고 프로젝트 설정으로 이동하여 앱을 추가하세요.

iOS와 Android의 대화창은 비슷하게 보입니다. 중요한 것은 앱에 사용하는 package id 입니다.

firebase-app-setup-ios

초기 단계 이후에 다운로드해야 하는 파일은 다음과 같습니다.

  • google-services.json Android용
  • file for Android iOS용

GoogleService-info.plist

file for iOS

다음으로 플랫폼을 설정합니다. Android Push Preparation은 다음 단계입니다. For Android, move the google-services.json __CAPGO_KEEP_0__ android/app/ 폴더.

android-push-file

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

iOS Push 설정

이 부분은 더 복잡합니다. 먼저 애플 개발자 계정의 식별자 목록에서 앱 ID를 생성하세요. Push Notifications 기능을 목록에서 선택하세요. App ID capability

__CAPGO_KEEP_0__ iOS Push ID

The Bundle ID 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.

iOS Developer Push Key

After downloading the .p8 file 파일을 업로드하세요. Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드하고 Key ID와 Team ID의 세부 정보를 iOS에서 입력하세요. Cloud Messaging Firebase 프로젝트 설정에서 Cloud Messaging 탭을 열고 파일을 업로드하고 Key ID와 Team ID의 세부 정보를 iOS에서 입력하세요.

firebase-upload-ios-key

Xcode 프로젝트를 변경하려면 다음 명령어를 실행하세요:

npx cap open ios

다운로드한 GoogleService-Info.plist 파일을 iOS 프로젝트에 복사하세요. Xcode 프로젝트 내부의 app/app 폴더에 파일을 끌어다 놓고 "복사할 필요가 있을 때 복사"를 선택하세요. Copy items if needed Firebase 의존성을 추가하려면 ios/App/Podfile 에서 새로운 Pod을 추가하세요. ios/App/Podfile.

자연 플랫폼을 업데이트하려면 다음 명령어를 실행하세요: Update the native platform with this command::

target 'App' do
  capacitor_pods
  # Add your Pods here
  pod 'Firebase/Messaging'
end

Update the native platform with this command:

npx cap update ios

Swift code을 원본으로 수정하여 Firebase와 등록하고 올바른 토큰을 앱에 반환하세요. ios/App/App/AppDelegate.swift Firebase와 등록하기 위해 Swift __CAPGO_KEEP_0__을 수정하고 올바른 토큰을 앱에 반환하세요.

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 프로젝트에서 푸시 알림 기능을 활성화하세요.

capacitor-xcode-capability

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

아이오닉 푸시 알림 통합

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

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

새로운 페이지를 동적 아이디로 포함시키기 위해 app/app-routing.module.ts 새로운 페이지를 동적 아이디로 포함시키기 위해 routing을 업데이트하세요.

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 { }

푸시 알림을 처리하는 서비스를 생성하세요. Firebase Cloud Messaging:

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() __CAPGO_KEEP_1__ __CAPGO_KEEP_2__:

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

__CAPGO_KEEP_3__ 세부 정보 페이지에서 정보를 처리하는 방법:

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_4__ 세부 정보를 표시하는 방법:

<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>

__CAPGO_KEEP_5__

ionic build
npx cap sync

앱을 빌드하고 변경 사항을 동기화하고 장치에 배포하세요.

Firebase를 사용하여 푸시 알림을 보내는 방법

Firebase를 사용하여 푸시 알림을 보내는 방법에 대한 여러 가지 방법

특정 장치 테스트

앱을 장치에 배포한 후, 등록 후 토큰을 확인하기 위해 콘솔 로그를 확인할 수 있습니다. 이 토큰을 사용하여 통합이 작동하는지 확인하기 위해 대상 테스트 푸시를 보내십시오. Firebase에서 Cloud Messaging 으로 이동하여 Send test message를 선택하십시오. 로그에서 장치 토큰을 추가하십시오.

firebase-test-push

모든 설정이 올바르게 구성되어 있다면, 장치에 푸시 알림을 볼 수 있을 것입니다.

Payload가 포함된 푸시 메시지

추가 정보를 지정하고 대상 플랫폼을 선택하여 푸시 알림에 추가 옵션을 보내려면, 동일한 페이지의 마법사를 따라하십시오. additional options __CAPGO_KEEP_0__

firebase-push-payload

In the 고급 설정 섹션에, Custom data key-value pair를 추가합니다. 예를 들어, key detailsId 사용하여 value를 선택할 수 있습니다. 이 데이터는 앱에서 id와 지정된 id로 details 페이지로 이동할 때 사용됩니다.

푸시 알림을 보내고 나서, 앱은 푸시 알림을 받고 id와 지정된 id로 details 페이지를 표시할 때 알림을 탭할 때

Firebase API

Firebase API를 사용하여 푸시 알림을 프로그래밍적으로 보내는 것도 가능합니다. 이 작업을 수행하려면 Firebase 서버 키 Firebase 프로젝트 설정에서 찾을 수 있습니다. Cloud Messaging tab.

Firebase 서버 키를 사용하여 Firebase API에 POST 요청을 보내고 필요한 페이로드와 함께 보내는 것이 가능합니다. Node.js와 함께 사용하는 예제는 다음과 같습니다. 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);
  }
});

__CAPGO_KEEP_0__ 서버 키와 장치 토큰을 실제로 대체하여 사용하세요. 스크립트를 실행하면 장치가 커스텀 페이로드와 함께 푸시 알림을 받을 것입니다. YOUR_SERVER_KEY 그것이 다입니다! Ionic __CAPGO_KEEP_0__ 앱에서 Firebase를 사용하여 푸시 알림을 성공적으로 통합했습니다. 이제 Android와 iOS 플랫폼에서 사용자에게 푸시 알림을 보내실 수 있습니다. YOUR_DEVICE_TOKEN Ionic __CAPGO_KEEP_0__ Push Notifications with Firebase: A Step-by-Step Guide에서 계속 진행하세요.

Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide를 사용하여 계획 및 기업 운영을 위한 마이그레이션을 계획하고 있습니다. 이에 대한 연결을 설정하세요.

Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide를 사용하여 계획 및 기업 운영을 위한 마이그레이션을 계획하고 있습니다. 이에 대한 연결을 설정하세요.

Ionic __CAPGO_KEEP_0__ Push Notifications with Firebase: A Step-by-Step Guide를 사용하여 계획 및 기업 운영을 위한 마이그레이션을 계획하고 있습니다. 이에 대한 연결을 설정하세요. Ionic Capacitor Push Notifications with Firebase: A Step-by-Step Guide를 사용하여 계획 및 기업 운영을 위한 마이그레이션을 계획하고 있습니다. 이에 대한 연결을 설정하세요. Ionic __CAPGO_KEEP_0__ Push Notifications with Firebase: A Step-by-Step Guide를 사용하여 계획 및 기업 운영을 위한 마이그레이션을 계획하고 있습니다. 이에 대한 연결을 설정하세요. Capgo 기업 서비스 Capgo 기업 서비스의 제품 워크플로우에 대해 아이오닉 기업 플러그인 대체 아이오닉 기업 플러그인 대체의 제품 워크플로우에 대해 Capgo 대체 Capgo 대체의 제품 워크플로우에 대해 Capgo 컨설팅 Capgo 컨설팅 및 Capgo 프리미엄 지원의 제품 워크플로우에 대해 Capgo 프리미엄 지원 Capgo 프리미엄 지원의 제품 워크플로우에 대해

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

앱 스토어 승인 기다리지 않고 Capgo를 통해 웹-layer 버그를 즉시 수정할 수 있습니다. 사용자는 배경에서 업데이트를 받으며 네이티브 변경 사항은 일반적인 검토 경로를 유지합니다.

시작하기

최신 블로그 글

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