[swift] Swift에서 푸시 알림을 사용하여 응원 알림 제공하기

앱 개발에서 사용자들에게 알림을 보내는 것은 매우 중요합니다. Swift에서는 푸시 알림을 사용하여 사용자에게 응원 알림을 제공하는 것이 간단하게 구현될 수 있습니다.

준비 사항

푸시 알림을 사용하기 위해서는 다음과 같은 준비 사항이 필요합니다:

  1. Apple Developer 계정: 앱 신청, 인증서 생성 및 앱 ID 등록을 위해 Apple Developer 계정이 필요합니다.
  2. Provisioning Profile: 앱을 푸시 알림 사용을 위해 사전에 설정한 Provisioning Profile이 필요합니다.
  3. Firebase 프로젝트: 푸시 알림을 위해 Firebase 프로젝트를 생성하고, Firebase에 iOS 앱을 추가해야 합니다.

Firebase 설정

  1. Firebase 콘솔에 로그인하고, Firebase 프로젝트를 생성합니다.
  2. 생성한 Firebase 프로젝트에 iOS 앱을 추가합니다. Bundle identifier를 입력한 후, GoogleService-Info.plist 파일을 다운로드합니다.

Xcode 설정

  1. Xcode에서 프로젝트를 열고, 앱의 Bundle Identifier를 Firebase 프로젝트에 등록한 것과 동일하게 설정합니다.
  2. 다운로드한 GoogleService-Info.plist 파일을 프로젝트에 추가합니다.

코드 구현

  1. AppDelegate.swift 파일을 열고 Firebase와 푸시 알림을 사용할 준비를 합니다.
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Firebase 초기화
        FirebaseApp.configure()
        
        // 푸시 알림 등록
        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self
        
        // 푸시 알림 권한 요청
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                // 알림 권한이 거부된 경우
            }
        }

        return true
    }
    
    // 푸시 알림 등록 성공 시 호출되는 메서드
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("Device Token: \(token)")
        // 푸시 알림 등록이 성공했을 때의 로직을 구현합니다.
    }
    
    // 푸시 알림 등록 실패 시 호출되는 메서드
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }

}

// 푸시 알림 처리를 위한 extension
extension AppDelegate: MessagingDelegate {

    // 토큰 갱신
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("FCM registration token: \(fcmToken)")
    }

    // 푸시 알림 수신
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
}

// 푸시 알림 처리를 위한 extension
extension AppDelegate: UNUserNotificationCenterDelegate {

    // 푸시 알림 수신 시 호출되는 메서드
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print("Received notification: \(userInfo)")
        
        // 알림을 클릭했을 때의 로직을 구현합니다.
        
        completionHandler()
    }
}
  1. 위에 작성한 코드를 통해 앱에서 푸시 알림을 수신하고 처리할 준비가 완료되었습니다. 이제 앱에서 push notification을 send하는 방법은 Firebase console의 Cloud Messaging을 통해 간단하게 수행할 수 있습니다.

결론

Swift에서 푸시 알림을 사용하여 응원 알림을 제공하는 방법을 알아보았습니다. Firebase를 활용하여 앱에서 푸시 알림을 받을 수 있고, 푸시 알림 수신시 자신만의 로직을 추가하여 사용자에게 응원 알림을 제공할 수 있습니다.