[ios] UserNotifications 프레임워크에서의 알림 행동 처리

앱에서 사용자에게 알림을 보내는 기능은 중요합니다. UserNotifications 프레임워크를 사용하여 iOS 앱에서 알림의 동작을 처리하는 방법에 대해 알아봅시다.

1. 알림 요청 생성

알림을 예약하거나 즉시 보내기 위해 UNNotificationRequest 개체를 생성해야 합니다. 이때, 알림의 내용과 액션을 정의합니다.

// 알림 콘텐츠 생성
let content = UNMutableNotificationContent()
content.title = "새로운 메시지"
content.body = "안녕하세요! 어떻게 지내세요?"

// 알림 요청 생성
let request = UNNotificationRequest(identifier: "notification-identifier", content: content, trigger: nil)

2. 알림 요청 등록

생성한 알림 요청을 UNUserNotificationCenter를 사용하여 등록합니다.

let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
    if let error = error {
        print("알림 요청 등록 실패: \(error)")
    } else {
        print("알림 요청 등록 성공!")
    }
}

3. 알림 행동 처리

사용자가 알림을 탭했을 때의 동작을 처리하기 위해 UNUserNotificationCenterDelegate 프로토콜을 준수하는 클래스를 정의하고 해당 동작을 구현합니다.

class NotificationManager: NSObject, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림에 대한 동작 처리
        print("사용자가 알림을 탭했습니다.")
    }
}

4. 대리자 설정

대리자를 설정하여 알림 행동을 처리할 클래스를 지정합니다.

let notificationManager = NotificationManager()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().delegate = notificationManager
    return true
}

UserNotifications 프레임워크를 사용하여 알림 요청 생성, 등록 및 행동 처리를 위한 기본적인 방법에 대해 알아보았습니다. 알림을 더욱 유연하게 처리하려면 UNNotificationCategory를 사용하여 알림 액션 및 카테고리를 정의하는 방법을 고려할 수 있습니다.

더 많은 정보는 Apple 개발자 문서에서 확인할 수 있습니다.