콘텐츠로 건너뛰기

고급 푸시 알림 예제

다음 가이드에서는 Braze SDK의 몇 가지 고급 푸시 알림 예제를 소개합니다.

필수 조건

이 기능을 사용하려면 먼저 Android Braze SDK를 통합해야 합니다. 푸시 알림도 설정해야 합니다.

커스텀 알림 레이아웃

Braze 알림은 데이터 메시지로 전송되므로, 앱이 백그라운드에서도 항상 응답하고 그에 맞는 동작을 수행할 수 있습니다(앱이 백그라운드에 있을 때 시스템이 자동으로 처리할 수 있는 알림 메시지와 대조적입니다). 따라서 앱은 알림 트레이에 전달되는 알림 내에 개인화된 UI 요소를 표시하는 등 경험을 커스터마이즈할 수 있습니다. 이 방식으로 푸시를 구현하는 것이 익숙하지 않을 수 있지만, Braze의 잘 알려진 기능 중 하나인 Push Stories는 커스텀 뷰 컴포넌트를 사용하여 매력적인 경험을 만드는 대표적인 예입니다!

IBrazeNotificationFactory 인터페이스를 사용하여 Braze 푸시 알림이 표시되는 방식을 커스터마이즈할 수 있습니다. BrazeNotificationFactory를 확장하면, Braze는 알림이 사용자에게 표시되기 전에 팩토리의 createNotification() 메서드를 호출합니다. 그런 다음 Braze 대시보드 또는 REST API를 통해 전송된 커스텀 키-값 페어가 포함된 페이로드를 전달합니다.

이 섹션에서는 야생 동물 구조 팀들이 가장 많은 올빼미를 구할 수 있는지 경쟁하는 새로운 게임 쇼의 진행자인 Superb Owl과 함께 작업합니다. 이들은 Android 앱에서 실시간 업데이트 알림을 활용하여 진행 중인 경기의 상태를 표시하고 알림을 실시간으로 동적 업데이트하려고 합니다.

Superb Owl이 표시하려는 실시간 업데이트로, 'Wild Bird Fund'와 'Owl Rescue' 간의 진행 중인 경기를 보여줍니다. 현재 4쿼터이며 점수는 2-4로 OWL이 리드하고 있습니다.

1단계: 커스텀 레이아웃 추가

프로젝트에 하나 이상의 커스텀 알림 RemoteView 레이아웃을 추가할 수 있습니다. 이는 알림이 축소되거나 확장될 때 표시되는 방식을 처리하는 데 유용합니다. 디렉토리 구조는 다음과 유사해야 합니다:

.
├── app/
└── res/
    └── layout/
        ├── liveupdate_collapsed.xml
        └── liveupdate_expanded.xml

각 XML 파일에서 커스텀 레이아웃을 만듭니다. Superb Owl은 축소 및 확장 RemoteView 레이아웃에 대해 다음과 같은 레이아웃을 만들었습니다:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/notification_title"
        style="@style/TextAppearance.Compat.Notification.Title"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>
샘플 코드 보기
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_gravity="center"

        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/team1logo"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/team_default1"/>

        <TextView
            android:id="@+id/team1name"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1.6"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/score"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="2-4"
            android:textColor="#555555"
            android:textAlignment="center"
            android:textSize="32sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/timeInfo"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>


    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/team2logo"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:src="@drawable/team_default2"/>

        <TextView
            android:id="@+id/team2name"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</LinearLayout>

2단계: 커스텀 알림 팩토리 생성

애플리케이션에서 BrazeNotificationFactory를 확장하는 MyCustomNotificationFactory.kt라는 새 파일을 만들어 커스텀 RemoteView 레이아웃이 표시되는 방식을 처리합니다.

다음 예제에서 Superb Owl은 진행 중인 경기에 대한 RemoteView 레이아웃을 표시하기 위해 커스텀 알림 팩토리를 만들었습니다. 다음 단계에서는 팀의 데이터를 활동에 매핑하는 getTeamInfo라는 새 메서드를 만듭니다.

샘플 코드 보기
import android.app.Notification
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.braze.models.push.BrazeNotificationPayload
import com.braze.push.BrazeNotificationFactory
import com.braze.push.BrazeNotificationUtils.getOrCreateNotificationChannelId
import com.braze.support.BrazeLogger.brazelog

class MyCustomNotificationFactory : BrazeNotificationFactory() {
    override fun createNotification(payload: BrazeNotificationPayload): Notification? {
        if (payload.extras.containsKey("live_update")) {
            val kvp = payload.extras
            val notificationChannelId = getOrCreateNotificationChannelId(payload)
            val context = payload.context

            if (context == null) {
                brazelog { "BrazeNotificationPayload has null context. Not creating notification" }
                return null
            }

            val team1 = kvp["team1"]
            val team2 = kvp["team2"]
            val score1 = kvp["score1"]
            val score2 = kvp["score2"]
            val time = kvp["time"]
            val quarter = kvp["quarter"]

            // Superb Owl will define the 'getTeamInfo' method in the next step.
            val (team1name, team1icon) = getTeamInfo(team1)
            val (team2name, team2icon) = getTeamInfo(team2)

            // Get the layouts to use in the custom notification.
            val notificationLayoutCollapsed = RemoteViews(BuildConfig.APPLICATION_ID, R.layout.liveupdate_collapsed)
            val notificationLayoutExpanded = RemoteViews(BuildConfig.APPLICATION_ID, R.layout.liveupdate_expanded)

            // Very simple notification for the small layout
            notificationLayoutCollapsed.setTextViewText(
                R.id.notification_title,
                "$team1 $score1 - $score2 $team2\n$time $quarter"
            )

            notificationLayoutExpanded.setTextViewText(R.id.score, "$score1 - $score2")
            notificationLayoutExpanded.setTextViewText(R.id.team1name, team1name)
            notificationLayoutExpanded.setTextViewText(R.id.team2name, team2name)
            notificationLayoutExpanded.setTextViewText(R.id.timeInfo, "$time - $quarter")
            notificationLayoutExpanded.setImageViewResource(R.id.team1logo, team1icon)
            notificationLayoutExpanded.setImageViewResource(R.id.team2logo, team2icon)

            val customNotification = NotificationCompat.Builder(context, notificationChannelId)
                .setSmallIcon(R.drawable.notification_small_icon)
                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setCustomContentView(notificationLayout)
                .setCustomBigContentView(notificationLayoutExpanded)
                .build()
            return customNotification
        } else {
            // Use the BrazeNotificationFactory for all other notifications
            return super.createNotification(payload)
        }
    }
}

3단계: 커스텀 데이터 매핑

MyCustomNotificationFactory.kt에서 실시간 업데이트가 표시될 때 데이터를 처리하기 위한 새 메서드를 만듭니다.

Superb Owl은 각 팀의 이름과 로고를 확장된 실시간 업데이트에 매핑하기 위해 다음 메서드를 만들었습니다:

class CustomNotificationFactory : BrazeNotificationFactory() {
    override fun createNotification(payload: BrazeNotificationPayload): Notification? {
        // Your existing code
        return super.createNotification(payload)
    }

    // Your new method
    private fun getTeamInfo(team: String?): Pair<String, Int> {
        return when (team) {
            "WBF" -> Pair("Wild Bird Fund", R.drawable.team_wbf)
            "OWL" -> Pair("Owl Rehab", R.drawable.team_owl)
            else  -> Pair("Unknown", R.drawable.notification_small_icon)
        }
    }
}

4단계: 커스텀 알림 팩토리 설정

애플리케이션 클래스에서 customBrazeNotificationFactory를 사용하여 커스텀 알림 팩토리를 설정합니다.

import com.braze.Braze

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        // Tell Braze to use your custom factory for notifications
        Braze.customBrazeNotificationFactory = MyCustomNotificationFactory()
    }
}

5단계: 활동 전송

/messages/send REST API 엔드포인트를 사용하여 사용자의 Android 기기로 푸시 알림을 전송할 수 있습니다.

curl 명령 예제

Superb Owl은 다음 curl 명령을 사용하여 요청을 전송했습니다:

curl -X POST "https://BRAZE_REST_ENDPOINT/messages/send" \
  -H "Authorization: Bearer {REST_API_KEY}" \
  -H "Content-Type: application/json" \
  --data '{
    "external_user_ids": ["USER_ID"],
    "messages": {
      "android_push": {
        "title": "WBF vs OWL",
        "alert": "2 to 4 1:33 Q4",
        "extra": {
          "live_update": "true",
          "team1": "WBF",
          "team2": "OWL",
          "score1": "2",
          "score2": "4",
          "time": "1:33",
          "quarter": "Q4"
        },
        "notification_id": "ASSIGNED_NOTIFICATION_ID"
      }
    }
  }'

요청 파라미터

키 설명
REST_API_KEY messages.send 권한이 있는 Braze REST API 키입니다.

Braze 대시보드에서 설정 > API 키로 이동하여 생성할 수 있습니다.
BRAZE_REST_ENDPOINT REST 엔드포인트 URL입니다. 엔드포인트는 인스턴스의 Braze URL에 따라 달라집니다.
USER_ID 알림을 전송할 사용자의 ID입니다.
messages.android_push.title 메시지의 제목입니다. 기본적으로 커스텀 알림 팩토리의 실시간 알림에는 사용되지 않지만, 대체 값으로 사용될 수 있습니다.
messages.android_push.alert 메시지의 본문입니다. 기본적으로 커스텀 알림 팩토리의 실시간 알림에는 사용되지 않지만, 대체 값으로 사용될 수 있습니다.
messages.extra 커스텀 알림 팩토리가 실시간 알림에 사용하는 키-값 페어입니다. 이 값에 임의의 문자열을 할당할 수 있지만, 이 예제에서는 live_updates를 사용하여 기본 푸시 알림인지 실시간 푸시 알림인지 판별합니다.
ASSIGNED_NOTIFICATION_ID 선택한 사용자의 실시간 알림에 할당할 알림 ID입니다. 이 ID는 해당 경기에 고유해야 하며, 나중에 기존 알림을 업데이트하기 위해 사용해야 합니다.

6단계: 활동 업데이트

기존 RemoteView 알림을 새 데이터로 업데이트하려면 messages.extra에 할당된 관련 키-값 페어를 수정한 다음, 동일한 notification_id를 사용하여 /messages/send 엔드포인트를 다시 호출합니다.

개인화된 푸시 알림

푸시 알림은 커스텀 뷰 계층 구조 내에서 사용자별 정보를 표시할 수 있습니다. 다음 예제에서는 API 트리거를 사용하여 사용자에게 개인화된 푸시 알림을 전송하여, 앱에서 특정 작업을 완료한 후 현재 진행 상황을 확인할 수 있도록 합니다.

개인화된 푸시 대시보드 예제

대시보드에서 개인화된 푸시를 설정하려면, 표시할 특정 카테고리를 등록한 다음 Liquid를 사용하여 표시하려는 관련 사용자 속성을 설정합니다.

개인화된 푸시 대시보드 예제

필수 조건

이 기능을 사용하려면 먼저 Swift Braze SDK를 통합해야 합니다. 푸시 알림도 설정해야 합니다.

알림 콘텐츠 앱 확장 기능

두 개의 푸시 메시지가 나란히 표시됩니다. 왼쪽 메시지는 기본 UI로 푸시가 어떻게 보이는지를 보여줍니다. 오른쪽 메시지는 커스텀 푸시 UI를 구현하여 만든 커피 적립 카드 푸시입니다.

알림 콘텐츠 앱 확장 기능은 푸시 알림 커스터마이징을 위한 훌륭한 옵션을 제공합니다. 알림 콘텐츠 앱 확장 기능은 푸시 알림이 확장될 때 앱 알림에 대한 커스텀 인터페이스를 표시합니다.

푸시 알림은 세 가지 방법으로 확장할 수 있습니다:

  • 푸시 배너를 길게 누르기
  • 푸시 배너를 아래로 스와이프하기
  • 배너를 가로로 스와이프하고 “보기”를 선택하기

이러한 커스텀 뷰는 인터랙티브 알림, 사용자 데이터로 채워진 알림, 그리고 전화번호와 이메일 같은 정보를 캡처할 수 있는 푸시 메시지를 포함한 다양한 유형의 콘텐츠를 표시하여 고객과 스마트하게 참여할 수 있는 방법을 제공합니다. Braze의 잘 알려진 기능 중 하나인 Push Stories는 푸시 알림 콘텐츠 앱 확장 기능이 어떤 모습인지를 보여주는 대표적인 예입니다!

요구 사항

Xcode의 새 타겟 템플릿 선택 화면에서 Application Extension 아래에 'Notification Content Extension'이 선택된 모습입니다.

  • 앱에 성공적으로 통합된 푸시 알림
  • 코딩 언어에 따라 Xcode에서 생성되는 다음 파일:

SWIFT

  • NotificationViewController.swift
  • MainInterface.storyboard

OBJECTIVE-C

  • NotificationViewController.h
  • NotificationViewController.m
  • MainInterface.storyboard

인터랙티브 푸시 알림

푸시 알림은 콘텐츠 앱 확장 내에서 사용자 동작에 응답할 수 있습니다. iOS 12 이상을 실행하는 사용자의 경우, 이는 푸시 알림을 완전한 인터랙티브 메시지로 전환할 수 있다는 것을 의미합니다! 이를 통해 프로모션과 앱에 인터랙티브 요소를 도입할 수 있는 흥미로운 옵션이 제공됩니다. 예를 들어, 푸시 알림에 사용자가 플레이할 수 있는 게임, 할인을 위한 룰렛 휠, 또는 리스팅이나 노래를 저장하는 “좋아요” 버튼을 포함할 수 있습니다.

다음 예제는 확장된 알림 내에서 사용자가 매칭 게임을 플레이할 수 있는 푸시 알림을 보여줍니다.

인터랙티브 푸시 알림의 각 단계가 어떻게 보일 수 있는지를 보여주는 다이어그램. 사용자가 푸시 알림을 눌러 인터랙티브 매칭 게임이 표시되는 순서를 나타냅니다.

대시보드 구성

인터랙티브 푸시 알림을 만들려면 대시보드에서 커스텀 뷰를 설정해야 합니다.

  1. Campaigns 페이지에서 Create Campaign을 클릭하여 새 푸시 알림 Campaign을 시작합니다.
  2. Compose 탭에서 Notification Buttons를 토글하여 켭니다.
  3. iOS Notification Category 필드에 커스텀 iOS 카테고리를 입력합니다.
  4. Notification Content Extension Target의 .plist에서 UNNotificationExtensionCategory 속성을 커스텀 iOS 카테고리로 설정합니다. 여기에 지정된 값은 Braze 대시보드의 iOS Notification Category에 설정된 값과 일치해야 합니다.
  5. UNNotificationExtensionInteractionEnabled 키를 true로 설정하여 푸시 알림에서 사용자 인터랙션을 활성화합니다.

푸시 메시지 작성기 설정에서 찾을 수 있는 알림 버튼 옵션. UNNotificationExtensionCategory가 "your_custom_category"로 설정되고, UNNotificationExtensionDefaultContentHidden이 1로 설정되며, UNNotificationExtensionInitialContentSizeRatio가 1로 설정된 NSExtension을 보여주는 plist.

개인화된 푸시 알림

두 대의 iPhone이 나란히 표시되어 있습니다. 첫 번째 iPhone은 푸시 메시지의 축소된 뷰를 보여줍니다. 두 번째 iPhone은 푸시 메시지의 확장된 버전을 표시하며, 과정 진행 상황, 다음 세션의 이름, 다음 세션 완료 기한을 보여줍니다.

푸시 알림은 콘텐츠 확장 내에서 사용자별 정보를 표시할 수 있습니다. 이를 통해 다양한 플랫폼에서 진행 상황을 공유하는 옵션을 추가하거나, 잠금 해제된 업적을 표시하거나, 온보딩 체크리스트를 표시하는 등 사용자 중심의 푸시 콘텐츠를 만들 수 있습니다. 이 예제는 사용자가 Braze 학습 과정에서 특정 작업을 완료한 후 표시되는 푸시 알림을 보여줍니다. 알림을 확장하면 사용자는 학습 경로를 통한 진행 상황을 확인할 수 있습니다. 여기서 제공되는 정보는 사용자별로 다르며, 세션이 완료되거나 특정 사용자 액션이 수행될 때 API 트리거를 활용하여 발송할 수 있습니다.

대시보드 구성

개인화된 푸시 알림을 만들려면 대시보드에서 커스텀 뷰를 설정해야 합니다.

  1. Campaigns 페이지에서 Create Campaign을 클릭하여 새 푸시 알림 Campaign을 시작합니다.
  2. Compose 탭에서 Notification Buttons를 토글합니다.
  3. iOS Notification Category 필드에 커스텀 iOS 카테고리를 입력합니다.
  4. Settings 탭에서 표준 Liquid를 사용하여 키-값 페어를 생성합니다. 메시지에 표시할 적절한 사용자 속성을 설정합니다. 이러한 뷰는 특정 고객 프로필의 특정 사용자 속성을 기반으로 개인화할 수 있습니다.
  5. Notification Content Extension Target의 .plist에서 UNNotificationExtensionCategory 속성을 커스텀 iOS 카테고리로 설정합니다. 여기에 지정된 값은 Braze 대시보드의 iOS Notification Category에 설정된 값과 일치해야 합니다.

네 세트의 키-값 페어로, "next_session_name"과 "next_session_complete_date"는 Liquid를 사용하여 API 트리거 속성정보로 설정되고, "completed_session count"와 "total_session_count"는 Liquid를 사용하여 커스텀 사용자 속성으로 설정됩니다.

키-값 페어 처리

didReceive 메서드는 알림 콘텐츠 앱 확장이 알림을 수신했을 때 호출됩니다. 이 메서드는 NotificationViewController 내에서 찾을 수 있습니다. 대시보드에서 제공된 키-값 페어는 userInfo 딕셔너리를 사용하여 코드에서 표현됩니다.

푸시 알림에서 키-값 페어 파싱

func didReceive(_ notification: UNNotification) {
  let userInfo = notification.request.content.userInfo

  guard let value = userInfo["YOUR-KEY-VALUE-PAIR"] as? String,
        let otherValue = userInfo["YOUR-OTHER-KEY-VALUE-PAIR"] as? String,
  else { fatalError("Key-Value Pairs are incorrect.")}

  ...
}
- (void)didReceiveNotification:(nonnull UNNotification *)notification {
  NSDictionary *userInfo = notification.request.content.userInfo;

  if (userInfo[@"YOUR-KEY-VALUE-PAIR"] && userInfo[@"YOUR-OTHER-KEY-VALUE-PAIR"]) {

  ...

  } else {
    [NSException raise:NSGenericException format:@"Key-Value Pairs are incorrect"];
  }
}

정보 수집 푸시 알림

푸시 알림은 콘텐츠 앱 확장 내에서 사용자 정보를 수집할 수 있으며, 푸시로 가능한 범위를 넓혀줍니다. 푸시 알림을 통해 사용자 입력을 요청하면 이름이나 이메일과 같은 기본 정보를 요청할 수 있을 뿐만 아니라, 사용자에게 피드백을 제출하거나 미완성된 고객 프로필을 완성하도록 안내할 수도 있습니다.

다음 흐름에서 커스텀 뷰는 상태 변경에 응답할 수 있습니다. 이러한 상태 변경 컴포넌트는 각 이미지에 표시되어 있습니다.

  1. 사용자가 푸시 알림을 받습니다.
  2. 푸시가 열립니다. 확장 후 푸시가 사용자에게 정보를 요청합니다. 이 예제에서는 사용자의 이메일 주소를 요청하지만, 어떤 종류의 정보든 요청할 수 있습니다.
  3. 정보가 제공되고 예상 형식에 맞으면 등록 버튼이 표시됩니다.
  4. 확인 뷰가 표시되고 푸시가 닫힙니다.

대시보드 구성

정보 수집 푸시 알림을 만들려면 대시보드에서 커스텀 뷰를 설정해야 합니다.

  1. Campaigns 페이지에서 Create Campaign을 클릭하여 새 푸시 알림 Campaign을 시작합니다.
  2. Compose 탭에서 Notification Buttons를 토글합니다.
  3. iOS Notification Category 필드에 커스텀 iOS 카테고리를 입력합니다.
  4. Settings 탭에서 표준 Liquid를 사용하여 키-값 페어를 생성합니다. 메시지에 표시할 적절한 사용자 속성을 설정합니다.
  5. 알림 콘텐츠 확장 타겟의 .plist에서 UNNotificationExtensionCategory 속성을 커스텀 iOS 카테고리로 설정합니다. 여기에 지정한 값은 Braze 대시보드의 iOS Notification Category 아래에 설정된 값과 일치해야 합니다.

예제에서 볼 수 있듯이 푸시 알림에 이미지를 포함할 수도 있습니다. 이렇게 하려면 리치 알림을 통합하고, Campaign에서 알림 스타일을 리치 알림으로 설정한 다음, 리치 푸시 이미지를 포함해야 합니다.

세 가지 키-값 페어가 포함된 푸시 메시지. 1. Braze ID를 가져오는 Liquid 호출로 설정된 "Braze_id". 2. "Braze Marketer Certification"으로 설정된 "cert_title". 3. "Certified Braze marketers drive..."로 설정된 "Cert_description".

버튼 액션 처리

각 실행 버튼은 고유하게 식별됩니다. 코드는 응답 식별자가 actionIdentifier와 동일한지 확인하고, 동일하면 사용자가 실행 버튼을 클릭했음을 인식합니다.

푸시 알림 실행 버튼 응답 처리

func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
  if response.actionIdentifier == "YOUR-REGISTER-IDENTIFIER" {
    // do something
  } else {
    // do something else
  }
}
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion {
  if ([response.actionIdentifier isEqualToString:@"YOUR-REGISTER-IDENTIFIER"]) {
    completion(UNNotificationContentExtensionResponseOptionDismiss);
  } else {
    completion(UNNotificationContentExtensionResponseOptionDoNotDismiss);
  }
}

푸시 닫기

푸시 알림은 실행 버튼을 누르면 자동으로 닫을 수 있습니다. 권장하는 세 가지 사전 설정된 푸시 닫기 옵션이 있습니다:

  1. completion(.dismiss) - 알림을 닫습니다
  2. completion(.doNotDismiss) - 알림이 열린 상태로 유지됩니다
  3. completion(.dismissAndForward) - 푸시가 닫히고 사용자가 애플리케이션으로 이동합니다
New Stuff!