본문으로 건너뛰기
강의

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

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

마틴 도나디우

마틴 도나디우

콘텐츠 마케터

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

이 튜토리얼에서는 아이오닉 Capacitor 앱에 Firebase를 사용하여 푸시 알림을 통합하는 방법을 배워보겠습니다. Firebase Cloud Messaging 지원을 제공하는 유지 관리 Capacitor 플러그인을 보려면 @capgo/capacitor-firebase-messaging을 참조하세요. 이 서비스를 사용할 필요는 없지만, 몇 가지 설정을 미리 구성해야 합니다. Firebase는 Android에 필수적이기 때문에, 데이터베이스를 사용하지 않고 알림을 보내는 데 쉽게 사용할 수 있습니다.

첫 번째로, 우리는 Capacitor를 활성화한 Ionic 앱을 만들고 패키지 ID를 지정할 것입니다. 패키지 ID__CAPGO_KEEP_0__가 생성한 native 플랫폼을 추가하기 전에 앱을 빌드할 것입니다.

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를 포함할 수 있습니다. 그러나 native 폴더가 이미 존재하는 경우, 모든 파일에서 ID를 교체해야 합니다. __CAPGO_KEEP_0__는 폴더를 한번만 생성하고 ID를 업데이트하지 않기 때문입니다. capacitor.config.json에서, 앱 ID를 포함하여 업데이트할 수 있는 옵션을 지정할 수 있습니다. 예를 들어, 배지 수를 업데이트하거나 푸시 시 소리를 재생하거나 알림이 도착했을 때 알림을 표시할 수 있습니다. __CAPGO_KEEP_0__.config.json __CAPGO_KEEP_0__Capacitor appIdappId capacitor__CAPGO_KEEP_0__

{
  "appId": "com.appdactic.devpush",
  "appName": "pushApp",
  "bundledWebRuntime": false,
  "npmClient": "npm",
  "webDir": "www",
  "plugins": {
    "SplashScreen": {
      "launchShowDuration": 0
    },
    "PushNotifications": {
      "presentationOptions": ["badge", "sound", "alert"]
    }
  },
  "cordova": {}
}

이제 앱 외부에서 푸시 알림을 구성해 보겠습니다.

파이어베이스 설정

먼저 새로운 파이어베이스 프로젝트를 만들거나 기존 프로젝트를 사용하세요. 새로운 앱이 있다면

If you have a new app, you should see 앱의 대시보드에서 프로젝트 설정 으로 이동하여 앱을 추가하세요. iOS와 Android의 dialog는 모두 유사하며 중요한 것은 패키지 ID를 사용하는 것입니다.

package id 앱의 대시보드 앱을 위한 것.

firebase-app-setup-ios

초기 단계 후, 다음 파일을 다운로드하세요.

  • google-services.json Android용 파일
  • GoogleService-info.plist iOS용 파일

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

Android Push Preparation

Android의 경우, 다운로드 한 google-services.json 파일을 android/app/ 폴더.

android-push-file

iOS를 위한 설정은 Android보다 더 복잡합니다. iOS Push Preparation

이 부분은 더 복잡합니다. iOS Push Preparation

애플 개발자 계정의 식별자 목록에서 앱 ID를 생성하세요. 앱 ID를 생성한 후 Push Notifications 기능을 선택하세요. ionic-ios-push-id The iOS Push Preparation

iOS Push Preparation

iOS Push Preparation Bundle ID Capacitor의 App ID와 Firebase 내의 App ID가 동일해야 합니다.

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

다운로드 받은 .p8 파일을 Firebase에 업로드하세요.

.p8 인증서를 업로드하세요. Cloud Messaging __CAPGO_KEEP_0__의 App ID와 Firebase 내의 App ID가 동일해야 합니다. Firebase 프로젝트 설정에서 탭을 클릭하고 파일을 업로드하고 Key ID와 Team ID의 세부 정보를 입력하세요.

firebase-upload-ios-key

이제 Xcode 프로젝트를 변경하기 위해 다음 명령어를 실행하세요.

npx cap open ios

다운로드 한 Firebase 파일을 iOS 프로젝트에 복사합니다. Xcode 프로젝트 내부의 app/app 폴더에 파일을 끌어다 놓고 선택하세요. Copy items if needed Firebase 의존성을 위한 새로운 Pod을 ios/App/Podfile에 추가하세요. 업데이트된 네이티브 플랫폼을 다음 명령어로 업데이트하세요..

Swift의 native __CAPGO_KEEP_0__을 ios/App/App/AppDelegate.swift에서 수정하세요. Copy the:

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

GoogleService-Info.plist

npx cap update ios

Modify the native Swift code in Copy items if needed 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 알림 기능을 활성화하세요.

capacitor-xcode-capability

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

아이온 Push 알림 통합

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

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

app/app-routing.module.ts의 라우팅을 업데이트 하세요. 새로운 페이지를 동적 아이디로 포함하세요: Push 알림을 처리하는 서비스를 services/fcm.service.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 { }

Push 알림을 호출하세요. Ionic Push Notification Integration:

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

Create a service and a new page in your Ionic project: 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>

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

ionic build
npx cap sync

이제 Firebase를 사용하여 푸시 알림을 보낼 수 있습니다.

Firebase를 사용하여 푸시 알림을 보내기

Firebase를 사용하여 푸시 알림을 보내기에는 여러 가지 방법이 있습니다.

특정 장치 테스트

장치에 앱을 배포한 후, 등록 후 토큰을 확인하기 위해 콘솔 로그를 확인하세요. 이 토큰을 사용하여 대상 테스트 푸시를 보내어 통합이 작동하는지 확인하세요. Firebase에서 Cloud Messaging 그리고 선택 테스트 메시지를 보내. 로그에서 디바이스 토큰을 추가하세요.

firebase-test-push

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

Payload를 포함한 푸시 메시지

추가 정보를 포함한 푸시 알림을 테스트하려면, 동일한 페이지의 마법사에 따라 일반 정보를 지정하고 대상 플랫폼을 선택하세요. 추가 추가 옵션 푸시 알림과 함께 Payload를 보내려면.

firebase-push-payload

푸시 알림을 테스트하려면 고급 설정 섹션, 추가하는 사용자 정의 데이터 키-값 pair. 예를 들어, 키 detailsId 및 선택한 값이 있습니다. 이 데이터는 앱에서 id와 지정된 id를 가진 세부 정보 페이지로 이동하는 데 사용됩니다.

푸시 알림을 보낸 후, 앱은 푸시 알림을 받고 푸시 알림을 탭할 때 지정된 id를 가진 세부 정보 페이지를 표시해야 합니다.

Firebase API를 사용하여

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

서버 키를 사용하여 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와 함께 사용하는 단계별 안내서를 사용하는 경우 이동 및 기업 운영을 계획하고 연결하려면 Capacitor Enterprise와 연결하세요. Enterprise Procurement Visual Signature Capgo Enterprise에서 제품 워크플로우를 위해 Capgo Enterprise Ionic Enterprise Plugin 대체 옵션 Ionic Enterprise Plugin 대체 옵션 Capgo 대체 옵션 Capgo 대체 옵션 Capgo 컨설팅 Capgo 컨설팅 Capgo 프리미엄 지원 Capgo 프리미엄 지원

Live updates for Capacitor apps

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

마틴의 인간 지원

시작하기

최신 블로그

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