[swift] Swift 푸시 알림

푸시 알림은 앱 사용자에게 중요한 정보나 업데이트를 실시간으로 전달하는 데 사용되는 강력한 도구입니다. Swift 언어를 사용하여 iOS 앱에 푸시 알림을 구현하는 방법에 대해 알아보겠습니다.

1. 앱 등록

푸시 알림을 사용하기 위해선 먼저 앱을 애플 푸시 알림 서비스에 등록해야 합니다. 애플 개발자 포털에 접속하여 앱 번들 ID와 서버 푸시 인증서를 생성하고, 앱에 필요한 권한과 설정을 설정해야 합니다.

2. APNs 연결

iOS 기기는 Apple Push Notification 서비스 (APNs)를 통해 푸시 알림을 수신합니다. APNs와의 연결을 설정해야 합니다. 앱의 AppDelegate.swift 파일에서 didFinishLaunchingWithOptions 메서드 내에서 APNs와의 연결 설정을 수행합니다.

import UserNotifications

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // APNs와의 연결 설정
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        // 알림 권한 요청 결과 처리
        if granted {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
    }

    return true
}

// APNs 등록 성공시 호출되는 메서드
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token: \(token)")
}

// APNs 등록 실패시 호출되는 메서드
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register for remote notifications: \(error.localizedDescription)")
}

위의 코드에서는 UNUserNotificationCenter를 사용하여 알림 권한을 요청하고, 알림 권한이 허용되면 registerForRemoteNotifications를 호출하여 APNs 등록을 수행합니다. APNs 등록이 성공하면 didRegisterForRemoteNotificationsWithDeviceToken 메서드가 호출되고, 실패하면 didFailToRegisterForRemoteNotificationsWithError 메서드가 호출됩니다.

3. 푸시 알림 전송

iOS 앱에 푸시 알림을 전송하려면 서버 측에서 알림을 작성하고 APNs에 전달해야 합니다. 이를 위해선 앱 서버에서 APNs에 요청을 보내는 방법을 알아야 합니다. APNs에 요청을 보내는 방법은 HTTP/2를 사용하는 방식과 네이티브 방식이 있습니다.

4. 푸시 알림 수신

앱이 백그라운드 또는 종료된 상태에서 푸시 알림을 수신하면 알림을 처리하기 위해 사용자의 알림 센터와 상호작용해야 합니다. UNUserNotificationCenterDelegate 프로토콜을 채택하여 푸시 알림 수신 및 처리 메서드를 구현할 수 있습니다.

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // APNs 등록 및 알림 권한 요청 등의 설정 코드

        // 푸시 알림 수신 및 처리를 위한 델리게이트 설정
        UNUserNotificationCenter.current().delegate = self

        return true
    }

    // 앱이 액티브 상태일 때 푸시 알림 수신시 호출되는 메서드
    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) {
        // 알림 클릭 이벤트 처리

        completionHandler()
    }
}

위 코드에서는 UNUserNotificationCenterDelegate 프로토콜을 채택하여 푸시 알림 수신 및 처리와 관련된 메서드를 구현하였습니다. willPresent 메서드는 앱이 액티브 상태일 때 푸시 알림이 도착하면 호출되며, didReceive 메서드는 푸시 알림을 터치하여 앱이 실행될 때 호출되는 메서드입니다.

푸시 알림 수신 및 처리 과정은 상기한 코드를 바탕으로 개발자가 필요한 기능에 맞게 추가 및 수정하여 구현할 수 있습니다.

결론

Swift를 사용하여 iOS 앱에 푸시 알림을 구현하는 방법에 대해 알아보았습니다. 푸시 알림은 앱 사용자에게 중요한 정보를 전달하기 위해 꼭 필요한 기능입니다. 개발자는 앱 등록, APNs 연결, 푸시 알림 전송, 푸시 알림 수신 등의 단계를 숙지하여 원하는 기능을 구현할 수 있습니다.