[swift] UserNotifications의 알림 액션 및 반응 처리

iOS 애플리케이션을 개발하는 동안 UserNotifications 프레임워크를 사용하여 사용자에게 알림을 보낼 수 있습니다. 이를 통해 사용자가 알림을 받았을 때 추가적인 작업을 수행할 수 있게끔 알림 액션을 제공할 수 있습니다. 이번 블로그에서는 UserNotifications 프레임워크를 사용하여 알림 액션을 추가하고 사용자가 알림에 반응하는 방법에 대해 알아보겠습니다.

알림 액션 추가하기

UserNotifications 프레임워크를 사용하여 알림에 액션을 추가하려면 UNNotificationAction 객체를 생성해야 합니다. 이 객체를 사용하여 사용자가 알림을 터치했을 때 실행될 동작을 정의할 수 있습니다.

다음은 예시 코드입니다:

import UserNotifications

// 알림 액션 생성
let likeAction = UNNotificationAction(identifier: "LikeAction",
                                      title: "좋아요",
                                      options: [.foreground])

let replyAction = UNTextInputNotificationAction(identifier: "ReplyAction",
                                                title: "답장",
                                                options: [.foreground],
                                                textInputButtonTitle: "전송",
                                                textInputPlaceholder: "답장을 입력하세요")

// 카테고리 생성
let category = UNNotificationCategory(identifier: "CustomCategory",
                                      actions: [likeAction, replyAction],
                                      intentIdentifiers: [],
                                      options: [])

// 등록
UNUserNotificationCenter.current().setNotificationCategories([category])

위의 코드는 “좋아요”와 “답장”이라는 두 가지 알림 액션을 생성하고, 이를 “CustomCategory”라는 카테고리에 등록하는 예시입니다.

알림에 반응하기

이제 알림 액션을 추가했으니, 사용자가 알림에 반응하는 방법을 살펴봅시다. 사용자가 알림의 액션을 선택했을 때, 알림 처리를 위해 delegate를 설정해야 합니다.

다음은 예시 코드입니다:

// UserNotifications delegate 설정
UNUserNotificationCenter.current().delegate = self

또한, 다음과 같이 UNUserNotificationCenterDelegate 프로토콜을 준수하여 사용자의 알림 액션에 대한 응답을 처리할 수 있습니다:

extension YourViewController: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        // 사용자의 알림 액션에 대한 처리 로직 구현
        if response.actionIdentifier == "LikeAction" {
            // "좋아요" 알림 액션 선택 시 실행될 동작
        } else if response.actionIdentifier == "ReplyAction" {
            // "답장" 알림 액션 선택 시 실행될 동작
        }
        completionHandler()
    }
}

위 코드에서 userNotificationCenter(_:didReceive:withCompletionHandler:) 메서드를 구현하여 사용자가 알림에 대한 반응을 처리합니다.

이제 UserNotifications 프레임워크를 사용하여 iOS 알림에 액션을 추가하고, 사용자가 알림에 반응하는 방법에 대해 알아보았습니다. 알림 액션을 활용하여 사용자와의 상호작용을 높일 수 있으며, 풍부한 사용자 경험을 제공할 수 있습니다.

더 많은 정보는 Apple Developer 문서를 참조하시기 바랍니다.