[swift] Swift에서 푸시 알림을 수신하는 방법

Swift에서 iOS 애플리케이션에 푸시 알림을 수신하는 기능을 구현하는 방법을 알아보겠습니다.

APNs (Apple Push Notification service) 설정하기

먼저, 푸시 알림을 사용하기 위해 Apple Developer 사이트에서 APNs 설정을 해야합니다.

  1. Apple Developer 사이트에 로그인하고, 애플리케이션의 Bundle Identifier에 해당하는 Provisioning Profile을 생성합니다.
  2. APNs 인증서를 생성하고, .p12 파일을 다운로드합니다.
  3. .p12 파일을 Keychain Access에 추가합니다.
  4. 인증서를 서버에 등록하고, 등록된 토큰을 푸시 알림 서비스에 전송합니다.

푸시 알림 수신 코드 작성하기

애플리케이션에서 푸시 알림을 수신하기 위해 다음과 같은 코드를 작성해야합니다.

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 푸시 알림 권한 요청
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            if granted {
                print("푸시 알림 권한이 허용되었습니다.")
                UNUserNotificationCenter.current().delegate = self
            }
        }
        
        application.registerForRemoteNotifications()
        
        return true
    }
    
    
    // APNs 등록 성공
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("APNs 등록 성공: \(token)")
        
        // 서버에 등록된 토큰을 전송하는 코드 작성
    }
    
    // APNs 등록 실패
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("APNs 등록 실패: \(error.localizedDescription)")
    }
    
    // 푸시 알림 수신
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }
    
    // 푸시 알림 처리
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 푸시 알림 처리 코드 작성
    }
}

동작 확인하기

위의 코드를 작성하고 실행하면, 애플리케이션에서 푸시 알림 권한 요청이 표시됩니다. 권한을 허용하면, 애플리케이션은 APNs에 등록되고 등록된 토큰이 출력됩니다. 푸시 알림이 도착하면, 화면 상단에서 알림이 표시됩니다.

이제, 서버에서 푸시 알림을 보내면, iOS 애플리케이션에서 해당 알림을 수신할 수 있습니다.

참고 자료