0Pricing
Swift Academy · 강의

알림 액션과 카테고리

알림에 대화형 액션을 추가합니다.

알림 액션과 카테고리은(는) CoddyKit의 무료 Swift Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Swift Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

인터랙티브 알림

알림은 텍스트를 표시하는 것 이상의 기능을 할 수 있습니다. 버튼을 제공할 수도 있습니다. 사용자는 앱을 열지 않고도 메시지에 답하거나 초대를 수락하거나 리마인더를 미룰 수 있습니다. 이는 동작을 카테고리로 묶어 구현합니다.

import UserNotifications
// Category = a set of actions
// Each delivered notification names its category
// so the system shows the right buttons

동작 정의

UNNotificationAction에는 식별자(나중에 이를 기준으로 구분합니다), 버튼에 표시되는 현지화된 제목, 그리고 .destructive나 앱을 실행하는 .foreground 같은 옵션이 있습니다.

import UserNotifications
let accept = UNNotificationAction(
    identifier: "ACCEPT",
    title: String(localized: "Accept"),
    options: [.foreground])
let decline = UNNotificationAction(
    identifier: "DECLINE",
    title: String(localized: "Decline"),
    options: [.destructive])

카테고리로 묶기

UNNotificationCategory는 카테고리 식별자 아래에 동작을 묶습니다. 배열에서 동작의 순서는 버튼의 순서가 됩니다. 앱이 시작될 때 알림 센터에 카테고리를 한 번 등록합니다.

import UserNotifications
let inviteCategory = UNNotificationCategory(
    identifier: "INVITE",
    actions: [accept, decline],
    intentIdentifiers: [],
    options: [])
UNUserNotificationCenter.current()
    .setNotificationCategories([inviteCategory])

카테고리로 알림 표시하기

버튼을 표시하려면 알림 콘텐츠의 categoryIdentifier에 등록된 카테고리를 설정해야 합니다. 원격 푸시의 경우 서버가 aps 딕셔너리 안에 "category": "INVITE"를 보냅니다.

import UserNotifications
let content = UNMutableNotificationContent()
content.title = String(localized: "New invite")
content.body = String(localized: "Ada invited you")
content.categoryIdentifier = "INVITE"

선택한 동작 처리하기

사용자가 버튼을 탭하면 델리게이트의 didReceive response가 실행되고, response.actionIdentifier에는 해당 동작 ID가 설정됩니다. 이를 기준으로 분기해 올바른 작업을 수행합니다.

import UserNotifications
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse
) async {
    switch response.actionIdentifier {
    case "ACCEPT":  print("accepted")
    case "DECLINE": print("declined")
    default:        break
    }
}

기본 및 닫기 식별자

항상 존재하는 시스템 식별자는 두 가지입니다. UNNotificationDefaultActionIdentifier는 사용자가 본문을 탭해 앱을 연 경우를 의미하고, UNNotificationDismissActionIdentifier는 사용자가 알림을 닫은 경우를 의미합니다. 사용자 지정 동작과 함께 이 식별자들도 처리하세요.

import UserNotifications
func route(_ id: String) {
    switch id {
    case UNNotificationDefaultActionIdentifier:
        print("opened the app")
    case UNNotificationDismissActionIdentifier:
        print("dismissed")
    default:
        print("custom action", id)
    }
}

텍스트 입력 동작

UNTextInputNotificationAction은 인라인 텍스트 필드를 표시하므로 빠른 답장에 적합합니다. 입력 상자에 표시할 버튼 제목과 자리 표시자도 추가합니다.

import UserNotifications
let reply = UNTextInputNotificationAction(
    identifier: "REPLY",
    title: String(localized: "Reply"),
    options: [],
    textInputButtonTitle: String(localized: "Send"),
    textInputPlaceholder: String(localized: "Message"))

입력한 텍스트 읽기

텍스트 동작의 응답은 UNTextInputNotificationResponse입니다. 이를 해당 유형으로 형 변환하면 사용자가 입력한 문자열인 userText를 읽을 수 있습니다.

import UserNotifications
func handle(_ response: UNNotificationResponse) {
    if let textResponse = response
        as? UNTextInputNotificationResponse {
        let message = textResponse.userText
        print("reply:", message)
    }
}

카테고리 옵션

카테고리 옵션으로 동작을 세부 조정할 수 있습니다. .customDismissAction은 닫기 이벤트를 델리게이트에 전달하고, .hiddenPreviewsShowTitle은 잠금 화면에서 미리보기가 숨겨져 있어도 제목을 표시하며, .allowInCarPlay는 CarPlay에서 표시할 수 있도록 합니다.

import UserNotifications
let category = UNNotificationCategory(
    identifier: "MESSAGE",
    actions: [reply],
    intentIdentifiers: [],
    options: [.customDismissAction,
              .hiddenPreviewsShowTitle])
_ = category

백그라운드 동작과 포그라운드 동작

.foreground 옵션이 없으면 동작이 앱을 앞으로 가져오지 않고 백그라운드에서 처리기를 실행합니다. 알림 미루기나 좋아요 처리에 적합합니다. .foreground가 있으면 앱이 실행되므로 UI를 표시할 수 있습니다. 사용자가 무언가를 볼 필요가 있는지에 따라 선택하세요.

import UserNotifications
let snooze = UNNotificationAction(
    identifier: "SNOOZE",
    title: String(localized: "Snooze"),
    options: []) // background, no app launch
let open = UNNotificationAction(
    identifier: "OPEN",
    title: String(localized: "Open"),
    options: [.foreground]) // launches app
_ = (snooze, open)

완전한 답장 흐름

텍스트 동작, 카테고리, 그리고 입력한 답장과 단순한 열기를 구분하는 처리기를 결합합니다. 이 패턴은 인라인 메시지 답장에 사용됩니다.

import UserNotifications
func handle(_ response: UNNotificationResponse) async {
    switch response.actionIdentifier {
    case "REPLY":
        let text = (response as?
            UNTextInputNotificationResponse)?.userText ?? ""
        print("send reply:", text)
    case UNNotificationDefaultActionIdentifier:
        print("open conversation")
    default:
        break
    }
}

빠른 확인

시스템이 어떤 버튼을 표시할지 어떻게 아는지 떠올려 보세요.

요약

인터랙티브 알림을 학습하셨습니다:

  • UNNotificationAction을 만들고(UNTextInputNotificationAction 포함), 이를 UNNotificationCategory로 묶습니다.
  • 앱 시작 시 카테고리를 등록하고, 콘텐츠의 categoryIdentifier 또는 푸시의 category를 설정해 버튼을 표시합니다.
  • 기본 및 닫기 식별자를 포함해 response.actionIdentifier를 처리하고, 답장의 경우 userText를 읽습니다.
  • 알림 미루기와 같은 백그라운드 동작에는 .foreground를 생략합니다.

자주 묻는 질문

“알림 액션과 카테고리” 강의는 무료인가요?

네 — “알림 액션과 카테고리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Swift Academy 강의 전체를 잠금 해제할 수 있습니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“알림 액션과 카테고리”에서 뭘 배우나요?

알림에 대화형 액션을 추가합니다. 브라우저에서 직접 실행하는 실습 코드로 Swift Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Swift Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Swift Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“알림 액션과 카테고리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Swift Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Swift Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 푸시 알림 등록하기
  2. 알림 페이로드 처리
  3. 백그라운드 작업과 새로 고침
  4. 알림 액션과 카테고리
← Swift Academy(으)로 돌아가기