본문으로 건너뛰기
강의

아이오닉 Capacitor 푸시 알림과 Firebase: 단계별 안내

아이오닉 Capacitor 앱에 Firebase를 사용하여 푸시 알림을 통합하는 방법에 대해 단계별로 설명합니다. Android와 iOS 플랫폼 모두 지원합니다.

기사 기여

마틴 도나디유

작가

발레리아

리뷰어

조던

편집자

아이오닉 Capacitor 푸시 알림과 Firebase: 단계별 안내

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@__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-firebase-messaging

Ionic Capacitor 푸시 먼저 Ionic 앱을 만들고 __CAPGO_KEEP_0__을 활성화한 다음, 앱의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

를 지정합니다. 이 id는 앱의 고유 식별자입니다. 그런 다음 앱을 빌드하고 네이티브 플랫폼을 추가합니다. 이미 앱이 있다면, capacitor.config.json을 변경하여 앱의 appId 를 포함할 수 있습니다. 그러나 네이티브 폴더가 이미 존재한다면, __CAPGO_KEEP_0__은 폴더를 한 번만 생성하기 때문에 모든 파일에서 id를 교체해야 합니다.Capacitor 업데이트하지 않습니다.. 앱 내에서 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 프로젝트를 만들거나 기존 프로젝트를 사용하세요. 새로운 프로젝트의 이름과 기본 옵션을 지정하세요. 새로운 앱이 있다면

If you have a new app, you should see 앱의 대시보드에서 "앱에 Firebase를 추가하여 시작하세요."라고 표시되어야 합니다. 그렇지 않다면 기어 아이콘을 클릭하고 대시보드의 설정으로 이동하세요. in your app’s dashboard. Otherwise, click the gear icon and go to 프로젝트 설정 앱을 추가하려면

iOS와 Android의 다이얼로그는 유사하며, 중요한 것은 앱에 사용하는 패키지 아이디 iOS

Firebase 앱 설정 후

google-services.json

  • Android용 파일 GoogleService-info.plist
  • iOS용 파일 다음으로 플랫폼을 설정합니다.

Next, configure the platforms.

안드로이드 푸시 준비

안드로이드의 경우, 다운로드 한 google-services.json 파일을 안드로이드 앱 폴더로 이동하세요. android-push-file 안드로이드 설정은 여기까지입니다. 이제 iOS를 설정해 보겠습니다.

iOS 푸시 준비

이 부분은 더 복잡합니다. 첫 번째로, 애플 개발자 계정의 식별자 목록에서 앱 ID를 생성하세요.

앱 ID를 생성한 후, 앱 ID에 대한 프로필을 생성하고, 앱 ID에 대한 프로필에서

Push Notifications 푸시 알림 푸시 알림 Push 알림 기능을 선택하세요 리스트에서 선택하세요.

ionic-ios-push-id

The Bundle ID Capacitor와 Firebase 내의 App ID와 동일해야 합니다.

이제 Key를 생성하세요 Apple Push Notifications 서비스 (APNs)를 활성화하세요 키의 최대 수를 초과한 경우 기존 키 또는 인증서를 사용할 수 있지만 프로세스는 더 복잡합니다.ios-developer-push-key

Push 알림 기능을 활성화하세요.

다운로드 받은 .p8 파일을 Firebase로 업로드하세요. Cloudflare의 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 의존성을 위한 새로운 Pod를 추가하세요. ios/App/Podfile:

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

업데이트를 위해 다음 명령어를 실행하세요:

npx cap update ios

수정할 native 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

앱을 빌드하고 Push Notifications를 통합하세요.

아이온 Push Notification 통합

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

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

app/app-routing.module.ts app/app-routing.module.ts 새로운 페이지를 동적 아이디로 포함하려면:

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

__CAPGO_KEEP_0__

파이어베이스를 사용한 푸시 알림 전송

파이어베이스를 사용하여 푸시 알림을 여러 가지 방법으로 전송할 수 있습니다.

특정 장치 테스트

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

firebase-test-push

푸시 알림이 올바르게 설정되어 있다면 장치에 푸시 알림이 표시되어야 합니다.

추가 정보를 포함한 푸시 알림 테스트

추가 정보를 포함한 푸시 알림을 테스트하려면, 같은 페이지의 마법사를 따라서 일반 정보를 지정하고 대상 플랫폼을 선택합니다. 추가 추가 옵션 푸시 알림과 함께 데이터를 전송하는 방법을 알아보세요.

firebase-push-payload

In the 고급 옵션 섹션에서 Custom data key-value pair을 추가하세요. 예를 들어, key detailsId 값을 사용할 수 있습니다. 이 데이터는 앱에서 id를 지정한 상세 페이지로 이동할 때 사용됩니다.

푸시 알림을 보내고 나면, 앱은 알림을 탭했을 때 id를 지정한 상세 페이지를 표시해야 합니다.

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 프리미엄 지원.

실시간으로 Capacitor 앱에 업데이트

웹-layer 버그가 활성화되면 Capgo를 통해 픽스를 배포하는 대신 앱 스토어 승인까지 며칠 기다리지 마십시오. 사용자는 배경에서 업데이트를 받으며 네이티브 변경 사항은 일반적인 검토 경로에 남게 됩니다.

마틴의 인간 지원

시작하기

최신 뉴스

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