[swift] Swift에서 Firebase의 푸시 알림을 이용한 사용자 알림 기능 구현

Firebase는 여러 기능을 제공하는 백엔드 서비스입니다. 그 중 하나인 푸시 알림은 사용자에게 알림을 보내는 기능을 제공합니다.

이번 포스트에서는 Swift에서 Firebase의 푸시 알림을 이용하여 사용자 알림 기능을 구현하는 방법을 알아보겠습니다.

1. Firebase 프로젝트 설정

Firebase 푸시 알림을 사용하기 위해서는 먼저 Firebase 콘솔에서 프로젝트를 설정해야 합니다. Firebase 콘솔에 접속하여 프로젝트를 생성하고, iOS 앱을 추가합니다. 앱 추가 시에는 앱 번들 ID를 입력해야 합니다. 이는 프로젝트의 Bundle Identifier와 일치해야 합니다.

Firebase 콘솔에서 iOS 앱을 추가한 후, 앱에 필요한 푸시 인증 키를 설정합니다. 이는 APNs 인증 키로, Apple 개발자 계정에서 생성할 수 있습니다. 생성한 인증 키를 Firebase 콘솔에 등록하면 Firebase와 APNs가 연결됩니다.

2. Firebase SDK 설치

Firebase SDK를 설치하기 위해 Cocoapods를 사용하겠습니다. Cocoapods를 사용하기 위해서는 먼저 Cocoapods가 설치되어 있어야 합니다. 설치되어 있지 않다면 터미널에서 아래 명령어를 실행해 Cocoapods를 설치합니다.

$ sudo gem install cocoapods

설치가 완료되었다면, 프로젝트의 루트 디렉토리에서 Podfile을 생성합니다.

$ pod init

위 명령어를 실행하면 프로젝트 디렉토리에 Podfile이 생성됩니다.

프로젝트의 Podfile을 열고, 아래 코드를 추가합니다.

pod 'Firebase/Core'
pod 'Firebase/Messaging'

Podfile에 필요한 Firebase 라이브러리를 추가한 뒤, 터미널에서 아래 명령어를 실행하여 라이브러리를 설치합니다.

$ pod install

3. Push 알림 등록

Push 알림을 등록하기 위해 AppDelegate.swift 파일을 열고, Firebase SDK와 관련된 코드를 추가합니다.

import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        UNUserNotificationCenter.current().delegate = self
        
        messaging().delegate = self
        messaging().requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
            if granted {
                print("Push notification authorization granted")
            } else {
                print("Push notification authorization denied")
            }
        }
        
        application.registerForRemoteNotifications()
        
        return true
    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: \(fcmToken ?? "")")
        
        // 서버에 토큰을 등록하는 로직을 추가할 수 있습니다.
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .sound, .badge])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림에 대한 응답을 처리하는 로직을 추가할 수 있습니다.
    }
}

위 코드에서 FirebaseApp.configure()은 Firebase를 초기화하는 코드입니다. messaging().delegate를 설정하여 푸시 알림 수신과 관련된 이벤트를 처리합니다.

또한 application.registerForRemoteNotifications()을 호출하여 앱에서 푸시 알림을 받을 수 있도록 등록합니다. messaging(didReceiveRegistrationToken:) 메서드는 푸시 알림을 위한 등록 토큰을 받는 메서드입니다.

위와 같이 Firebase와 iOS 알림 관련 코드를 추가한 뒤, 앱을 실행하고 디바이스 토큰을 확인하여 Firebase에 등록합니다.

4. 서버에서 알림 보내기

Firebase에 사용자의 토큰을 등록한 후에는 서버에서 알림을 보낼 수 있습니다. Firebase에서 제공하는 Admin SDK를 사용하여 서버에서 알림을 보내는 방법을 알아보겠습니다.

먼저, Node.js와 npm을 설치합니다. 그리고 터미널에서 아래 명령어를 실행하여 Firebase Admin SDK를 설치합니다.

$ npm install firebase-admin --save

Firebase 콘솔에서 설정한 인증 정보를 사용하여 Admin SDK를 초기화합니다.

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

이제 알림을 보낼 수 있습니다. 아래 코드는 모든 사용자에게 알림을 보내는 예시입니다.

var message = {
  notification: {
    title: '알림 제목',
    body: '알림 내용'
  },
  topic: 'all-users' // 토픽명은 원하는 대로 지정할 수 있습니다.
};

admin.messaging().send(message)
  .then((response) => {
    console.log('알림 성공:', response);
  })
  .catch((error) => {
    console.log('알림 실패:', error);
  });

위 코드에서 notification 객체에는 알림의 제목과 내용을 설정할 수 있습니다. topic은 알림을 받을 대상을 지정하는 것으로, 원하는 대상에 알림을 보내도록 설정할 수 있습니다.

이와 같은 방식으로 Firebase의 푸시 알림을 사용하여 사용자 알림 기능을 구현할 수 있습니다. Firebase의 다양한 기능을 활용하여 앱의 사용성을 향상시킬 수 있습니다.

더 자세한 내용은 아래 링크를 참고하세요.