[IOS] Apple Push Notification 디바이스 토큰을 발급받는 과정

디바이스 토큰(Device Token)은 iOS 기기가 푸시 알림을 수신할 준비가 되었음을 나타내는 고유한 식별자입니다. 이 토큰은 Apple Push Notification service (APNs)로부터 발급받아야 합니다. 디바이스 토큰을 발급받는 과정은 다음과 같습니다:

  1. 앱에 푸시 알림 기능을 추가: 푸시 알림을 사용하려면 iOS 앱에 푸시 알림을 처리할 수 있는 코드를 추가해야 합니다. 이는 AppDelegate와 같은 앱의 핵심 클래스에서 처리되는 경우가 많습니다.

  2. APNs 등록 요청: iOS 앱이 처음 실행되거나, 사용자가 푸시 알림을 허용하는 동작을 수행한 시점에 디바이스 토큰을 발급받기 위해 APNs에 등록 요청을 보냅니다.

  3. 디바이스 토큰 수신: APNs는 등록 요청을 받고, iOS 기기에게 고유한 디바이스 토큰을 발급해줍니다.

  4. 디바이스 토큰 저장: 앱은 APNs로부터 받은 디바이스 토큰을 앱 내부에 저장하거나 서버로 전달하여 푸시 알림을 보낼 때 사용합니다.

iOS 앱에서 디바이스 토큰을 발급받는 코드는 아래와 같이 AppDelegate 클래스의 didRegisterForRemoteNotificationsWithDeviceToken 메서드를 이용하여 처리할 수 있습니다 (Swift로 예시):

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 푸시 알림 권한 요청
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            // 알림 권한 요청 결과 처리
            if granted {
                application.registerForRemoteNotifications()
            }
        }
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // 디바이스 토큰 발급 성공 시 처리
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("디바이스 토큰: \(token)")
        // 디바이스 토큰을 서버에 전송하거나 앱 내부에 저장하는 등의 작업을 수행합니다.
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // 디바이스 토큰 발급 실패 시 처리
        print("푸시 알림 등록 실패: \(error.localizedDescription)")
    }

    // ... 다른 AppDelegate 메서드들 ...
}

위의 코드에서 didRegisterForRemoteNotificationsWithDeviceToken 메서드에서 디바이스 토큰을 발급받게 됩니다. 토큰은 Data 형태로 제공되며, 이를 문자열로 변환하여 사용할 수 있습니다. 이 토큰을 서버로 전송하거나 앱 내부에 저장하여 푸시 알림을 보낼 때 사용하면 됩니다.