Firebase로 iOS 앱에 푸시 알림 구현하기
푸시 알림은 사용자와의 지속적인 관계를 유지하는 데 중요한 요소입니다. 이번 글에서는 Firebase Cloud Messaging(FCM)을 활용하여 iOS 앱에 푸시 알림을 구현하는 방법을 자세히 알아보겠습니다.
Firebase 프로젝트 설정하기
먼저 Firebase 프로젝트를 생성하고 iOS 앱을 추가해야 합니다. Firebase 콘솔에서 '클라우드 메세지'를 클릭하여 필요한 인증 키를 설정합니다.
APNs 인증 키 설정
- 애플 개발자 계정에서 키를 발급받아야 합니다.
- 발급받은
.p8파일을 Firebase 콘솔에 업로드합니다. - 키 ID와 팀 ID를 입력하여 인증 키 발급을 완료합니다.
주의사항: 배포용으로 사용할 경우, 애플 개발자 콘솔에서 키를 발급할 때 기본값인 'Sandbox'를 'Sandbox & Production'으로 변경해야 출시 후에도 알림이 정상적으로 작동합니다.
Firebase SDK 통합하기
CocoaPods를 사용하여 Firebase 메시징 라이브러리를 프로젝트에 추가합니다:
// Podfile
pod 'Firebase/Messaging'
그 후 pod install 명령어를 실행하여 라이브러리를 설치합니다.
다운로드한 GoogleService-Info.plist 파일을 Xcode 프로젝트에 추가합니다.
AppDelegate 설정하기
AppDelegate.swift 파일에 다음 코드를 추가하여 Firebase를 초기화하고 푸시 알림을 처리합니다:
import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
import FirebaseCore
import FirebaseMessaging
import UserNotifications
@UIApplicationMain
class AppDelegate: RCTAppDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// Firebase 초기화
FirebaseApp.configure()
// Firebase Messaging 설정
Messaging.messaging().delegate = self
// 알림 권한 요청
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if let error = error {
print("알림 권한 요청 실패: \(error.localizedDescription)")
}
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
// React Native 설정
self.moduleName = "diaryFront"
self.dependencyProvider = RCTAppDependencyProvider()
self.initialProps = [:]
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func bundleURL() -> URL? {
#if DEBUG
return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
// APNs 토큰을 FCM에 등록
override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
// FCM 토큰 업데이트 처리
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("FCM 등록 토큰: \(fcmToken ?? "토큰 없음")")
}
}
FCM 토큰 관리하기
FCM 토큰은 각 기기를 식별하는 고유한 값으로, 이 토큰을 서버에 저장하여 특정 기기에 알림을 보낼 수 있습니다.
func sendTokenToServer(_ token: String?) {
guard let token = token else { return }
// 서버에 토큰을 등록하는 API 호출
// 예: API.registerToken(token)
}
백엔드에서 알림 보내기
백엔드 서버에서 Firebase Cloud Messaging API를 사용하여 알림을 전송할 수 있습니다. 다음은 Node.js를 사용한 간단한 예시입니다:
// Notification 함수
async function sendNotification(token, title, body) {
const message = {
notification: {
title,
body,
},
android: {
priority: 'high',
notification: {
channelId: 'default',
},
},
apns: {
payload: {
aps: {
alert: {
title,
body,
},
sound: 'default',
badge: 1,
'mutable-content': 1,
'content-available': 1,
},
},
headers: {
'apns-push-type': 'alert',
'apns-priority': '10',
},
},
token,
};
try {
const response = await admin.messaging().send(message);
return { success: true, response };
} catch (error) {
console.error('Error sending message:', error);
return { success: false, error };
}
}
// 매일 특정 시간에 알림 보내기 (예: 매일 11:43 AM)
cron.schedule('43 11 * * *', async () => {
try {
const [test] = await db.query('SELECT ~ FROM ~ WHERE ~ IS NOT NULL');
for (const ~ of ~) {
if (~) {
await sendNotification(
~.~,
'일기 작성 시간입니다 ! 📝',
'오늘 하루는 어떠셨나요? 소중한 추억을 기록해보세요.'
);
}
}
} catch (error) {
console.error('Error sending daily notifications:', error);
}
}, { timezone: "Asia/Seoul" });
알림 보내는 js는 바뀐 부분도 많지만 기본적인 틀은 이런식입니다.
마무리
이제 Firebase Cloud Messaging을 사용하여 iOS 앱에 푸시 알림을 구현하는 방법에 대해 알아보았습니다. 이 시스템을 활용하면 사용자에게 중요한 정보를 실시간으로 전달하고 앱의 참여도를 높일 수 있습니다.
푸시 알림 구현 시 사용자 경험을 고려하여 필요한 경우에만 알림을 보내고, 사용자가 알림 설정을 관리할 수 있는 기능도 제공하는 것이 좋습니다.
'RN 개발일지' 카테고리의 다른 글
| React-Native 개발일지 - [ 네비게이터 ] (0) | 2025.02.26 |
|---|---|
| React-Native 개발일지 - [ 스크롤 ] (0) | 2025.02.26 |
| "너의 하루는" 다이어리 앱 소개 (0) | 2025.02.25 |
| 개인정보 처리방침 (0) | 2025.02.20 |
| 맥북 에어 M3 React Native 초기 환경 설정 (0) | 2025.02.02 |