푸시

Prev Next

Classic/VPC 환경에서 이용 가능합니다.

개발자가 서버 또는 클라우드에서 모바일 장치로 효율적으로 메시지를 전송할 수 있게 합니다. 푸시를 사용하면 알림 메시지를 모바일 앱과 웹 앱에 전송할 수 있습니다. 푸시는 iOS, Android 애플리케이션을 포함한 다양한 플랫폼을 지원합니다.

대시보드 설정

푸시 서비스를 사용하려면 먼저 각 플랫폼의 키를 준비한 뒤 대시보드에 설정해야 합니다.

FCM 푸시 키 생성 방법

FCM 푸시 키를 발급하려면 아래 절차를 순서대로 진행해 주십시오.

  1. Firebase Console > 프로젝트 설정 > 클라우드 메시징 > 서비스 계정 관리를 클릭해 주십시오.
    ko-gamepot3-push01.png

  2. Google Cloud > 서비스 계정 > 생성되어 있는 이메일 계정을 선택해 주십시오.
    ko-gamepot3-push02.png

  3. 키 > 키 추가 > 새 키 만들기 > 키 유형은 'JSON'으로 선택 후 [만들기] 버튼을 클릭해 주십시오.

    • 기존에 만들어 둔 키가 있다면, 해당 파일을 사용해도 됩니다.
      ko-gamepot3-push03.png

APNS 인증키 생성 방법

APNs 인증키는 iOS 푸시 발송을 위해 반드시 필요하므로 다음 절차에 따라 발급해 주십시오.

  1. 애플 개발자 사이트 로그인 > Certificates, IDs & Profiles > 키 선택 > [+] 버튼을 클릭하여 신규 키를 생성해 주십시오.

    • 푸시 인증키는 최대 2개까지만 생성할 수 있습니다.
      ko-gamepot3-push04.png
  2. Key Name을 입력하고, Apple Push notifications service (APNs)를 활성화해 주십시오.
    ko-gamepot3-push05.png

  3. [Register] 버튼을 누르고 인증키를 발급해 주십시오.
    ko-gamepot3-push06.png

  4. Key ID를 확인하고 다운로드해 주십시오.

    • 다운로드한 파일의 확장자는 .p8입니다.
    • 키 파일은 한 번만 다운로드할 수 있습니다.
      ko-gamepot3-push07.png

대시보드 키 설정 방법

발급받은 키는 GAMEPOT 대시보드에 등록해야 정상적으로 푸시를 발송할 수 있습니다.

  • 프로젝트 설정 - 연동 - Google Android (FCM) Configuration

    • SenderID: Firebase 콘솔 > 프로젝트 설정 > 클라우드 메시징 > 발신자 ID
    • Private Key (json file): FCM 푸시 키 생성 방법에서 생성한 JSON 파일을 메모장 혹은 텍스트 편집기와 같은 프로그램으로 연 뒤 전체 내용을 복사하여 등록합니다.
  • 프로젝트 설정 - 연동 - Apple iOS (APNs) Configuration

    • Certificate: APNs 인증키 생성 방법에서 생성한 .p8 파일을 메모장 혹은 텍스트 편집기와 같은 프로그램으로 연 뒤 전체 내용을 복사하여 등록합니다.
    • Key ID: APNs 인증키 생성 방법에서 생성한 .p8 파일의 Key ID를 등록합니다.
    • Team ID: 애플 개발자 사이트 '멤버십 세부사항'의 팀 ID를 입력합니다.
    • Bundle ID: 앱 패키지의 Bundle Identifier 값을 입력합니다.

푸시 설정 방법

각 플랫폼별로 SDK 설정을 완료해야 푸시 알림을 정상적으로 수신할 수 있습니다.

AOS Native

GAMEPOT Android SDK를 사용하는 경우 아래 절차에 따라 푸시 연동을 구성해 주십시오.

Firebase Messaging 연동

Android 푸시 수신을 위해서는 FCM(Firebase Cloud Messaging) 연동이 필요합니다. FCM을 연동하려면 아래 절차를 따르세요.

  1. Firebase 프로젝트 생성 및 앱 등록

    • Firebase 콘솔에서 새 프로젝트를 생성합니다.
    • 프로젝트에 Android 앱을 추가하고, 패키지명을 입력합니다.
    • google-services.json 파일을 다운로드하여 앱 모듈의 루트 디렉터리에 추가합니다.
  2. build.gradle 설정

    • 모듈 app의 build.gradle.kts에 아래 플러그인과 의존성을 추가합니다.
    • Kotlin:
    plugins {
         id("com.google.gms.google-services")
    }
    dependencies {
         implementation("com.google.firebase:firebase-messaging-ktx:23.4.1")
    }
    
    • 프로젝트 루트의 build.gradle.kts에 아래 플러그인을 추가합니다.
    • Kotlin:
    plugins {
         id("com.google.gms.google-services") version "4.4.1" apply false
    }
    
  3. FCM 초기화 및 토큰 관리

    • initialize가 성공하면 SDK가 알림 권한(Android 13 이상은 POST_NOTIFICATIONS)을 요청합니다(setAutoPush 기본값 true). 푸시를 사용하지 않는다면 initialize 전에 setAutoPush(false)를 호출해 주십시오.
    • 대시보드에 FCM 설정(SenderID)을 저장했다면 SDK가 initialize 중에 푸시 토큰을 받아 보관하고, 로그인에 성공하면 서버에 등록합니다.
    • 앱에 google-services.json을 적용했다면 SDK에 포함된 MyFirebaseMessagingService가 토큰이 새로 발급되거나 갱신될 때 NBase.setPushToken(token)을 자동으로 호출합니다. 이미 발급된 토큰은 NBase.initializeFirebaseMessaging()을 호출해 가져올 수 있으며, NBase.getPushToken()으로 현재 값을 확인할 수 있습니다.
    • 토큰이 로그인 이후에 발급되었거나 갱신된 경우에는 푸시 상태 설정의 setPushState로 토큰을 함께 전달해 주십시오.
    • 이 밖의 푸시 설정 메서드는 푸시 설정 메서드를 참조해 주십시오.
  4. 문제 해결

    • Default FirebaseApp is not initialized 오류가 발생하면 gradle 설정을 다시 확인해 주십시오.
    • google-services.json 파일이 없을 경우 Firebase 콘솔에서 다시 다운로드한 뒤 올바른 위치에 추가해 주십시오.

푸시 알림 아이콘 설정

푸시 메시지를 수신했을 때 알림 바에 표시할 작은 아이콘을 설정할 수 있습니다. 별도로 설정하지 않을 경우 SDK에 포함된 기본 이미지를 사용하며, 게임에 맞는 아이콘을 직접 설정할 수 있습니다.

Android Asset Studio를 이용해 제작하면 자동으로 폴더별 이미지가 생성되어 편리합니다.

푸시 알림 아이콘을 설정하는 방법은 다음과 같습니다.

  1. 아래 경로에 res/drawable 폴더들을 각각 생성한 후 크기에 맞는 아이콘 이미지 파일을 추가합니다.
    • 아래 표는 해상도별 폴더와 권장 아이콘 크기를 안내합니다.
폴더명 크기
res/drawable-mdpi/ 24x24
res/drawable-hdpi/ 36x36
res/drawable-xhdpi/ 48x48
res/drawable-xxhdpi/ 72x72
res/drawable-xxxhdpi/ 96x96
  1. 이미지 파일의 이름을 ic_stat_nbase_small로 변경합니다.

iOS Native

GAMEPOT iOS SDK를 사용하는 경우 아래 절차에 따라 푸시 연동을 구성해 주십시오.

푸시 기능 초기화

푸시 기능을 활성화하려면 AppDelegate를 통해 토큰 등록 로직을 구성해 주십시오. 알림 권한 요청과 원격 알림 등록(registerForRemoteNotifications)은 initialize가 성공한 뒤 SDK가 수행합니다(setAutoPush 기본값 true). 아래 예제처럼 앱에서 직접 요청해도 되며, 이미 허용하거나 거부한 경우 시스템 창은 다시 표시되지 않습니다. iOS SDK는 FCM을 거치지 않으므로, 앱이 APNs에서 받은 토큰을 NBase.setPushToken으로 SDK에 전달해야 합니다.

AppDelegate 설정 예제는 Swift와 Objective-C 각각 아래와 같습니다. Swift 예제에서 AppDelegate는 UNUserNotificationCenterDelegate를 채택해야 합니다.

  • Swift:
import NBase
import UserNotifications

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

func registerForRemoteNotifications() {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
        if granted {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        } else {
            print("The push notification permission has been denied")
        }
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    NBase.setPushToken(token: token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    NBase.setPushToken(token: "")
}

// 앱이 화면에 떠 있는 동안에도 알림을 표시합니다.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.banner, .sound, .badge])
}

Objective-C 예제의 NBaseBridge는 SDK(CocoaPods)에 포함된 클래스가 아니라 GitHub에서 별도로 내려받는 NBaseBridge.swift에 있는 클래스입니다. Objective-C 프로젝트에서는 Objective-C 프로젝트에서 사용하기를 참고해 이 파일을 프로젝트에 추가한 뒤 사용해 주십시오.

  • Objective-C:
#import "[ProjectName]-Swift.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;

    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)
                         completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            });
        } else {
            NSLog(@"Push permission denied");
        }
    }];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [self stringWithDeviceToken:deviceToken];
    [NBaseBridge.shared setPushToken:token];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Failed to register for remote notifications: %@", error);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
            
    completionHandler(UNNotificationPresentationOptionBanner | 
                     UNNotificationPresentationOptionSound | 
                     UNNotificationPresentationOptionBadge);
}

- (NSString *)stringWithDeviceToken:(NSData *)deviceToken {
    NSUInteger length = deviceToken.length;
    if (length == 0) {
        return nil;
    }
    const unsigned char *buffer = deviceToken.bytes;
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
    for (int i = 0; i < length; ++i) {
        [hexString appendFormat:@"%02x", buffer[i]];
    }
    return [hexString copy];
}
주의
  • setAutoPush가 true(기본값)이면 initialize가 성공한 뒤 SDK가 알림 권한 요청과 registerForRemoteNotifications를 호출합니다. 푸시를 사용하지 않는다면 initialize 전에 NBase.setAutoPush(enable: false)를 호출해 주십시오.
  • setPushToken에는 APNs가 발급한 토큰을 16진수 문자열로 변환해 전달해 주십시오. FCM 토큰이 아닙니다.
  • 푸시 토큰은 로그인에 성공할 때 서버에 등록됩니다. 토큰이 SDK에 전달된 뒤에 로그인하도록 구성해 주십시오.

개발 서명 빌드와 TestFlight, App Store 빌드는 사용하는 APNs 환경이 다르므로 푸시 테스트 절차도 다릅니다. 자세한 내용은 iOS 개발 빌드(샌드박스) 푸시 테스트를 참조해 주십시오.

이미지 푸시

iOS 앱에서 알림 이미지를 수신하고 처리하기 위해 알림 서비스 확장을 추가해야 합니다.

  • Swift:
  1. Xcode 프로젝트의 TARGETS에서 Notification Service Extension을 추가합니다.
  2. 생성된 Notification Service Extension 모듈의 NotificationService.swift 파일을 아래와 같이 수정합니다.
import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        guard let bestAttemptContent = bestAttemptContent,
              let userInfo = request.content.userInfo as? [String: Any] else {
            contentHandler(request.content)
            return
        }

        let imageURL = userInfo["imageUrl"] as? String ??
                      userInfo["gcm.notification.image"] as? String

        guard let imageURL = imageURL, !imageURL.isEmpty else {
            contentHandler(bestAttemptContent)
            return
        }

        downloadAndAttachImage(urlString: imageURL) { attachment in
            if let attachment = attachment {
                bestAttemptContent.attachments = [attachment]
            }
            DispatchQueue.main.async {
                contentHandler(bestAttemptContent)
            }
        }
    }

    private func downloadAndAttachImage(urlString: String, completionHandler: @escaping (UNNotificationAttachment?) -> Void) {
        guard let url = URL(string: urlString.trimmingCharacters(in: .whitespaces)) else {
            completionHandler(nil)
            return
        }

        let session = URLSession(configuration: .ephemeral)
        let task = session.downloadTask(with: url) { (location, response, error) in
            if let error = error {
                completionHandler(nil)
                return
            }
            
            guard let location = location else {
                completionHandler(nil)
                return
            }

            let fileManager = FileManager.default
            let tmpDirectory = NSTemporaryDirectory()
            let tmpFile = "image_\(Date().timeIntervalSince1970).png"
            let tmpPath = (tmpDirectory as NSString).appendingPathComponent(tmpFile)
            let tmpURL = URL(fileURLWithPath: tmpPath)

            do {
                if fileManager.fileExists(atPath: tmpPath) {
                    try fileManager.removeItem(atPath: tmpPath)
                }
                try fileManager.moveItem(at: location, to: tmpURL)

                let attachment = try UNNotificationAttachment(
                    identifier: UUID().uuidString,
                    url: tmpURL,
                    options: [UNNotificationAttachmentOptionsTypeHintKey: "public.png"]
                )
                completionHandler(attachment)
            } catch {
                completionHandler(nil)
            }
        }

        task.resume()

        DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
            task.cancel()
        }
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}
  • Objective-C:
  1. Xcode 프로젝트의 TARGETS에서 Notification Service Extension을 추가합니다.
  2. 생성된 Notification Service Extension 모듈의 NotificationService.m 파일을 아래와 같이 수정합니다.
#import "NotificationService.h"

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    NSDictionary *userInfo = request.content.userInfo;
    NSString *imageUrl = userInfo[@"imageUrl"];
    if (!imageUrl) {
        imageUrl = userInfo[@"gcm.notification.image"];
    }

    if (imageUrl && imageUrl.length > 0) {
        [self downloadAndAttachImage:imageUrl completionHandler:^(UNNotificationAttachment *attachment) {
            if (attachment) {
                self.bestAttemptContent.attachments = @[attachment];
            }
            self.contentHandler(self.bestAttemptContent);
        }];
    } else {
        self.contentHandler(self.bestAttemptContent);
    }
}

- (void)downloadAndAttachImage:(NSString *)urlString completionHandler:(void(^)(UNNotificationAttachment *attachment))completionHandler {
    NSURL *url = [NSURL URLWithString:[urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
    if (!url) {
        completionHandler(nil);
        return;
    }

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
    [[session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if (error) {
            completionHandler(nil);
            return;
        }
        
        if (!location) {
            completionHandler(nil);
            return;
        }

        NSString *tmpDirectory = NSTemporaryDirectory();
        NSString *tmpFile = [NSString stringWithFormat:@"image_%f.png", [[NSDate date] timeIntervalSince1970]];
        NSString *tmpPath = [tmpDirectory stringByAppendingPathComponent:tmpFile];
        NSURL *tmpURL = [NSURL fileURLWithPath:tmpPath];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:tmpPath]) {
            [fileManager removeItemAtPath:tmpPath error:nil];
        }

        NSError *moveError = nil;
        [fileManager moveItemAtURL:location toURL:tmpURL error:&moveError];
        if (moveError) {
            completionHandler(nil);
            return;
        }

        NSError *attachmentError = nil;
        UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:[[NSUUID UUID] UUIDString]
                                                                                              URL:tmpURL
                                                                                          options:@{UNNotificationAttachmentOptionsTypeHintKey: @"public.png"}
                                                                                            error:&attachmentError];

        if (attachmentError) {
            completionHandler(nil);
            return;
        }

        completionHandler(attachment);
    }] resume];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [session invalidateAndCancel];
    });
}

- (void)serviceExtensionTimeWillExpire {
    if (self.contentHandler && self.bestAttemptContent) {
        self.contentHandler(self.bestAttemptContent);
    }
}

네이티브 로컬 푸시 등록 및 취소

Android, iOS 네이티브 SDK에서 지정한 시간이 지난 뒤 기기에서 직접 알림을 표시하는 로컬 푸시를 등록하고 취소할 수 있습니다. 알림을 표시하려면 기기의 알림 권한이 허용되어 있어야 합니다.

  • Kotlin:
// pushId를 빈 문자열로 전달하면 SDK가 ID를 생성합니다. after의 단위는 초입니다.
val pushId = NBase.sendLocalPush(
    activity,
    "event-reminder",
    "이벤트 알림",
    "이벤트가 곧 시작됩니다.",
    10L,
    "",
    "",
    "default"
)

// 특정 로컬 푸시 취소
NBase.cancelLocalPush(activity, pushId)

// 등록된 모든 로컬 푸시 취소
NBase.cancelAllLocalPush(activity)
  • Java:
NBase nBase = NBase.INSTANCE;
String pushId = nBase.sendLocalPush(activity, "event-reminder", "이벤트 알림", "이벤트가 곧 시작됩니다.", 10L, "", "", "default");

nBase.cancelLocalPush(activity, pushId);
nBase.cancelAllLocalPush(activity);
  • Swift:
let pushId = NBase.sendLocalPush(
    pushId: "event-reminder",
    title: "이벤트 알림",
    message: "이벤트가 곧 시작됩니다.",
    after: 10
)

NBase.cancelLocalPush(pushId: pushId)
NBase.cancelAllLocalPush()
  • Objective-C:
NSString *pushId = [NBaseBridge.shared sendLocalPush:@"event-reminder"
                                               title:@"이벤트 알림"
                                             message:@"이벤트가 곧 시작됩니다."
                                               after:10
                                            imageUrl:nil
                                                 url:nil
                                             channel:@"default"];

[NBaseBridge.shared cancelLocalPush:pushId];
[NBaseBridge.shared cancelAllLocalPush];

sendLocalPush 매개변수는 다음과 같습니다.

Key Type Description Required
activity Activity 현재 액티비티(Android만 해당) O
pushId String 로컬 푸시 고유 ID. 비우면 SDK가 생성 X
title String 알림 제목 O
message String 알림 내용 O
after Long(Android) / Int(iOS) 알림을 표시할 때까지의 대기 시간(초) X
imageUrl String 알림에 표시할 이미지 URL X
url String 알림을 눌렀을 때 열 URL X
channel String 알림 채널. iOS 기본값은 default X

sendLocalPush는 등록한 로컬 푸시의 ID를 반환합니다. Java에서는 기본값이 적용되지 않으므로 모든 인자를 전달해 주십시오. iOS는 after가 0이어도 최소 0.1초 뒤에 표시합니다. setAutoPush(false)로 설정했다면 푸시 설정 메서드의 requestPermission으로 알림 권한을 요청해 주십시오.

참고

Android 12 이상에서 앱에 정확한 알람 예약 권한이 없으면 지정한 시간보다 늦게 알림이 표시될 수 있습니다.

Unity

Unity 기반 프로젝트에서는 Android 및 iOS 빌드를 모두 고려하여 구성 파일과 의존성을 설정해야 합니다.

Firebase 푸시 설정 (Unity)

Unity에서 Android 푸시 알림(Firebase Messaging)을 사용할 때 필요한 설정과 필요하지 않은 설정을 안내합니다.

Unity 프로젝트에는 google-services.json 파일을 추가하지 않아도 됩니다. NBase SDK는 이 파일을 읽지 않고, initialize 중에 서버가 전달하는 FCM 설정과 대시보드에 저장한 SenderID로 Firebase 앱을 직접 만들어 푸시 토큰을 받습니다. 따라서 다음 설정이 필요합니다.

  1. 대시보드 프로젝트 설정 > 연동의 Google Android (FCM) Configuration에서 Enable Push with FCM 토글을 켜고 SenderID와 **Private Key (json file)**를 저장해 주십시오. 자세한 내용은 대시보드 키 설정 방법과 푸시 알림 연동 설정을 참조해 주십시오.
  2. 다음 절의 Unity FCM SDK 추가에서 firebase-messaging 라이브러리를 프로젝트에 추가해 주십시오. SDK는 이 라이브러리를 포함하지 않으므로 추가하지 않으면 푸시 토큰을 받지 못합니다.
참고

Unity 프로젝트에서 Firebase Unity SDK처럼 NBase SDK와 별도로 Firebase 플러그인을 함께 사용하는 경우에는 해당 플러그인의 안내에 따라 google-services.json을 추가해야 할 수 있습니다. 이 파일은 해당 플러그인을 위한 것이며, NBase SDK의 푸시 동작에는 영향을 주지 않습니다.

Unity FCM SDK 추가

NBase SDK Unity 3.0.18 이상에서는 Unity 에디터의 Tools > GamePotSDK > Dependency Manager를 열고 (AOS Push) Firebase Push Notification을 선택한 뒤 Apply Dependencies를 클릭해 주십시오. 필요한 라이브러리가 Assets/NBaseSDK/Editor/NBaseSDKDependencies.xml에 반영되고 Android 의존성 해석이 실행됩니다.

수동으로 설정해야 하는 경우에는 /Assets/NBaseSDK/Editor/NBaseSDKDependencies.xml 파일에 다음 의존성을 추가해 주십시오.

  • XML:
<dependencies>
    <androidPackages>
        <androidPackage spec="io.nbase:nbasesdk:3.0.99">
            <repositories>
                <repository>https://repo.nbase.io/repository/nbase-releases</repository>
            </repositories>
        </androidPackage>
        <androidPackage spec="com.google.firebase:firebase-messaging-ktx:23.4.1" />
    </androidPackages>
    <iosPods>
    </iosPods>
</dependencies>

수동 설정 후에는 Assets > External Dependency Manager > Android Resolver > Force Resolve를 클릭하여 라이브러리 의존성을 적용해 주십시오.

푸시 알림 아이콘 설정(유니티)

Unity 푸시 메시지를 수신했을 때 알림 바에 표시할 작은 아이콘을 설정할 수 있습니다. 별도로 설정하지 않으면 SDK에 포함된 기본 이미지를 사용하며, 게임에 맞는 아이콘을 직접 설정할 수 있습니다.

Android Asset Studio를 이용해서 제작하면 자동으로 폴더별로 이미지가 생성되어 편리합니다.

유니티 엔진 202x 이후 버전의 푸시 알림 아이콘을 설정하는 방법은 다음과 같습니다.

  1. 아래 경로에 res/drawable 폴더들을 각각 생성한 후 그 크기에 맞는 아이콘 이미지 파일을 추가합니다.
    • 아래 표는 리소스 경로와 해상도를 설명합니다.
폴더명 크기
/Assets/Plugins/Android/GamePotResources.androidlib/res/drawable-mdpi/ 24x24
/Assets/Plugins/Android/GamePotResources.androidlib/res/drawable-hdpi/ 36x36
/Assets/Plugins/Android/GamePotResources.androidlib/res/drawable-xhdpi/ 48x48
/Assets/Plugins/Android/GamePotResources.androidlib/res/drawable-xxhdpi/ 72x72
/Assets/Plugins/Android/GamePotResources.androidlib/res/drawable-xxxhdpi/ 96x96
  1. mainTemplate.gradle에 해당 라이브러리를 추가합니다.
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project('GamePotResources.androidlib') // 추가
    ...
}
  1. 이미지 파일의 이름을 ic_stat_nbase_small로 변경합니다.

푸시 자동 설정(Unity)

SDK의 자동 푸시 동작 설정 값을 지정하거나 조회할 수 있습니다. 기본값은 true이며, true이면 initialize가 성공한 뒤 SDK가 알림 권한을 요청합니다. 푸시를 사용하지 않는다면 initialize 전에 false로 설정해 주십시오.

// initialize 호출 전에 설정합니다.
NBaseSDK.NBase.setAutoPush(false);
bool isAutoPush = NBaseSDK.NBase.getAutoPush();
주의
  • setAutoPush는 initialize를 호출하기 전에 설정해 주십시오.
  • setAutoPush가 true이면 Android(13 이상)와 iOS 모두 initialize가 성공한 뒤 알림 권한 요청 팝업이 표시됩니다. false이면 SDK가 요청하지 않습니다.
  • 원하는 시점에 직접 요청하려면 NBaseSDK.NBase.requestPermission("notification")을 호출해 주십시오.
  • iOS에서는 SDK의 iOS 플러그인이 받은 푸시 토큰을 SDK에 전달합니다.
  • Unity Standalone(PC)에서는 푸시를 지원하지 않으며 setAutoPush는 동작하지 않고 getAutoPush는 항상 false를 반환합니다.

포그라운드 푸시 표시 설정(Android)

NBase SDK Unity 3.0.16 이상에서 Android 앱이 포그라운드에 있을 때도 푸시 알림을 표시할지 설정할 수 있습니다.

// true: 포그라운드에서도 푸시 알림 표시
NBaseSDK.NBase.setForegroundPush(true);

bool enabled = NBaseSDK.NBase.getForegroundPush();
Key Type Description
enable Boolean 포그라운드 푸시 알림 표시 여부
enabled Boolean 현재 설정된 포그라운드 푸시 알림 표시 여부

포그라운드 푸시 표시 설정은 Android에서만 사용할 수 있으며 기본값은 true입니다. iOS와 Unity Standalone(PC)에서는 경고 로그만 출력되고 getForegroundPush는 false를 반환합니다.

로컬 푸시 등록 및 취소

NBase SDK Unity 3.0.15 이상의 Android, iOS에서 지정한 시간 후 로컬 푸시 알림을 표시할 수 있습니다.

string pushId = NBaseSDK.NBase.sendLocalPush(
    "event-reminder",
    "이벤트 알림",
    "이벤트가 곧 시작됩니다.",
    10,
    "",
    "",
    "default"
);

// 특정 로컬 푸시 취소
NBaseSDK.NBase.cancelLocalPush(pushId);

// 등록된 모든 로컬 푸시 취소
NBaseSDK.NBase.cancelAllLocalPush();
Key Type Description Required
pushId String 로컬 푸시 고유 ID. 빈 문자열이면 SDK가 ID를 생성합니다. X
title String 알림 제목 O
message String 알림 내용 O
after Long 알림을 표시할 때까지의 대기 시간(초) O
imageUrl String 알림에 표시할 이미지 URL X
url String 알림을 클릭했을 때 열 URL X
channel String 알림 채널 ID X

sendLocalPush()는 등록된 로컬 푸시의 ID를 반환합니다. 알림 표시를 위해 Android와 iOS의 알림 권한이 허용되어 있어야 합니다. Unity Standalone(PC)에서는 로컬 푸시를 지원하지 않으며 sendLocalPush()가 빈 문자열을 반환합니다.

푸시 상태

사용자가 푸시 수신 동의 여부를 직접 관리할 수 있도록 앱 내에서 상태 변경 기능을 구현해 주십시오.

약관 동의창에서 받은 광고성 푸시와 야간 광고성 푸시 동의 값도 이 상태에 저장됩니다. 약관 동의창에 푸시 항목이 표시되는 조건은 약관 동의창의 푸시 항목 표시 조건을 참조해 주십시오.

푸시 상태 설정

푸시 수신을 위해서는 푸시 상태를 true로 설정해야 합니다. 푸시 상태 변경에 사용되는 각 파라미터의 의미는 아래와 같습니다.

파라미터 설명

  • push: 푸시 수신 동의 상태 (true/false)
  • night: 야간 푸시 동의 상태 (한국 시간 기준, true/false)
  • ad: 광고성 푸시 동의 상태 (true/false). 광고성 푸시 값이 false이면 일반/야간 푸시 설정과 관계없이 푸시가 발송되지 않습니다.
  • token: 푸시 토큰 값. iOS에서는 이 값 대신 NBase.setPushToken으로 저장한 토큰이 서버로 전달됩니다.

푸시 수신 여부 설정을 변경하려면 로그인 이후 아래 코드를 호출해 주십시오.

  • Kotlin:
val pushToken = NBase.getPushToken()
val pushState = com.nbase.sdk.model.PushState(
    push = enable,
    night = night,
    ad = ad,
    token = pushToken
)
NBase.setPushState(pushState) { state, e ->
    if (e != null) {
        // failed.
    } else {
        // succeeded.
    }
}
  • Java:
boolean enable = true;
boolean night = false;
boolean ad = true;

NBase nBase = NBase.INSTANCE;
String pushToken = nBase.getPushToken();
com.nbase.sdk.model.PushState pushState = new com.nbase.sdk.model.PushState(
    enable,
    night,
    ad,
    pushToken
);
nBase.setPushState(pushState, (state, e) -> {
    if (e != null) {
        // failed.
    } else {
        // succeeded.
    }
    return null;
});
  • Swift:
NBase.setPushState(enable: enable, ad: ad, night: night, token: NBase.getPushToken()) { result in
    switch result {
    case .success(let state):
        // succeeded.
        print("push: \(state?.push ?? false)")
    case .failure(let error):
        // failed.
        print(error.errorDescription ?? "")
    }
}
  • Objective-C:
BOOL enable = YES;
BOOL night = NO;
BOOL ad = YES;
NSString *token = [NBaseBridge.shared getPushToken];

[NBaseBridge.shared setPushState:enable night:night ad:ad token:token :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // failed.
    } else {
        // succeeded.
    }
}];
참고

Unity에서 setPushState와 getPushState는 Android와 iOS에서만 사용할 수 있으며 로그인한 상태에서 호출해야 합니다. Unity Standalone(PC)과 에디터에서는 FEATURE_DEPRECATED 오류가 반환됩니다. 매개변수 순서는 enable, ad, night, token입니다.

  • C#:
bool push = true;
bool ad = true;
bool night = false;
string token = ""; // 빈 값을 넣으면 기존 토큰 유지

NBaseSDK.NBase.setPushState(push, ad, night, token, (pushState, error) => {
    if (error != null)
    {
        // failed.
    }
    else
    {
        // succeeded.
    }
});
주의
  • Android의 푸시 상태 기본값은 false입니다. 반면 iOS는 앱을 실행할 때마다 푸시, 광고성 푸시, 야간 푸시 값이 true로 시작합니다.
  • iOS에서 signIn(소셜 로그인)으로 로그인하면서 약관 동의창을 거치지 않으면 이 값이 로그인 성공 시 서버로 전송됩니다. 자동 로그인(signInLastLoggedIn)과 자격 증명, 비밀번호, 게스트 로그인은 서버에 저장된 값을 먼저 읽어 사용합니다.
  • 약관 동의창을 사용하지 않는 앱은 signIn 직후 setPushState로 사용자가 선택한 값을 다시 설정해 주십시오.

푸시 상태 확인

사용자의 현재 푸시 동의 상태를 확인하려면 아래 예제를 참조해 주십시오.

  • Kotlin:
NBase.getPushState() { state, e ->
    if (e != null) {
        // failed.
    } else {
        // succeeded.
    }
}
  • Java:
NBase nBase = NBase.INSTANCE;
nBase.getPushState((state, e) -> {
    if (e != null) {
        // failed.
    } else {
        // succeeded.
    }
    return null;
});
  • Swift:
NBase.getPushState() { result in
    switch result {
    case .success(let state):
        // succeeded.
        print("push: \(state?.push ?? false)")
    case .failure(let error):
        // failed.
        print(error.errorDescription ?? "")
    }
}
  • Objective-C:
[NBaseBridge.shared getPushState:^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // failed.
    } else {
        // succeeded.
    }
}];
  • C#:
NBaseSDK.NBase.getPushState((pushState, error) => {
    if (error != null)
    {
        // failed.
    }
    else
    {
        // succeeded.
    }
});

푸시 상태 설정과 확인의 콜백으로 전달되는 PushState 객체의 필드는 다음과 같습니다. Unity에서는 필드 이름이 대문자로 시작합니다.

Key Unity Key Type Description
push Push Boolean 푸시 수신 동의 상태
night Night Boolean 야간 푸시 동의 상태
ad Ad Boolean 광고성 푸시 동의 상태
token Token String 푸시 토큰

푸시 설정 메서드

푸시 토큰과 포그라운드 알림 표시를 설정할 수 있습니다.

Android와 iOS 네이티브 SDK의 푸시 설정 메서드는 다음과 같습니다.

메서드 플랫폼 설명
setAutoPush(enable) / getAutoPush() Android, iOS 기본값 true. true이면 initialize가 성공한 뒤 SDK가 알림 권한을 요청(iOS는 registerForRemoteNotifications까지). 푸시를 사용하지 않으면 initialize 전에 false로 설정
setForegroundPush(enable) / getForegroundPush() Android 앱이 화면에 떠 있는 동안에도 푸시 알림을 표시할지 여부. 기본값은 true
setPushToken(token) / getPushToken() Android, iOS 푸시 토큰 저장 및 조회. 저장한 토큰은 로그인 성공 시 또는 setPushState 호출 시 서버로 전달
initializeFirebaseMessaging() Android 앱의 기본 Firebase 설정으로 토큰을 받아 setPushToken에 저장
requestPermission(activity, Permission.NOTIFICATION) / requestPermission(permission: "notification") Android, iOS 원하는 시점에 알림 권한 요청(Android는 13 이상). iOS는 허용되면 registerForRemoteNotifications까지 호출
  • Kotlin:
// 앱이 화면에 떠 있는 동안에는 알림을 표시하지 않으려면
NBase.setForegroundPush(false)

// 앱의 기본 Firebase 설정으로 토큰을 받으려면
NBase.initializeFirebaseMessaging()
val token = NBase.getPushToken()
  • Java:
NBase nBase = NBase.INSTANCE;
nBase.setForegroundPush(false);
nBase.initializeFirebaseMessaging();
String token = nBase.getPushToken();
주의
  • 알림 권한은 initialize가 성공한 뒤 setAutoPush가 true이면 SDK가 요청합니다. 푸시를 사용하지 않는다면 initialize 전에 setAutoPush(false)를 호출해 주십시오.
  • iOS 토큰 전달은 푸시 기능 초기화를 참조해 주십시오.
  • setEnablePush는 Android와 iOS에서 의미가 다르고 Android에서는 동작하지 않으므로 사용하지 마십시오.

푸시 테스트 방법(모바일)

모바일 환경에서 푸시 알림이 정상적으로 동작하는지 확인하려면 아래 테스트 절차를 참조해 주십시오.

  • 게임팟 대시보드: 대시보드 > 운영 > 메시지 > 푸시 알림 메뉴에서 푸시 발송 여부를 확인할 수 있습니다.

  • Android (Firebase 콘솔) 테스트: Firebase console > 프로젝트 선택 > Messaging > 캠페인에서 새 캠페인 버튼을 클릭하여 테스트 메시지를 발송해 주십시오.
    ko-gamepot-push02.png

    ko-gamepot-push03.png

    앱에서 수집한 푸시 토큰을 입력한 뒤 테스트 버튼을 누르면 해당 토큰으로 발송 여부를 확인할 수 있습니다.

  • iOS (CloudKit Console) 테스트: CloudKit Console > Push Notifications 메뉴에서 새 Notifications를 생성해 주십시오.
    CloudKit_Push Notifications.png

    Device Token과 Payload를 입력한 뒤 발송 결과를 확인해 주십시오.

iOS 개발 빌드(샌드박스) 푸시 테스트

iOS 개발 빌드와 배포 빌드는 APNs 환경이 다르므로 빌드 종류에 맞는 절차로 푸시를 테스트해 주십시오.

iOS SDK는 FCM을 거치지 않고, 앱이 didRegisterForRemoteNotificationsWithDeviceToken에서 받은 APNs 토큰을 NBase.setPushToken으로 전달받아 로그인할 때 서버에 등록합니다. 대시보드의 프로젝트 설정 > 연동 > Apple iOS (APNs) Configuration에는 sandbox와 production을 고르는 항목이 없으며, .p8 인증키와 Key ID, Team ID, 번들 ID만 등록합니다.

빌드 종류별 차이

빌드 종류에 따라 앱의 aps-environment 값과 푸시 테스트 방법이 달라집니다.

빌드 종류별 차이는 다음과 같습니다.

구분 Xcode 실행(개발 서명) Ad Hoc TestFlight App Store
aps-environment development production production production
APNs 환경 개발(sandbox) 운영 운영 운영
대시보드 화이트리스트 개발 유형 IP 등록 필요 불필요 불필요 불필요
푸시 발송 대상 플랫폼 샌드박스 iOS 또는 전체 iOS 또는 전체 iOS 또는 전체
주의
  • 개발 서명 빌드에서 받은 토큰은 개발 환경 전용이고, TestFlight와 App Store 빌드에서 받은 토큰은 운영 환경 전용입니다. 두 환경의 토큰은 서로 바꿔서 사용할 수 없습니다. 같은 기기에서 빌드 종류를 바꾸면 토큰이 새로 발급됩니다.
  • 대시보드에는 sandbox와 production 환경을 선택하는 설정이 없습니다. 개발 환경 푸시는 아래 절차의 화이트리스트와 샌드박스 디바이스 등록으로 구분합니다.

개발 빌드(샌드박스) 테스트 절차

Xcode로 개발 빌드를 실행하는 경우 샌드박스 푸시를 테스트하는 방법은 다음과 같습니다.

  1. Xcode의 Signing & Capabilities에서 Push Notifications와 Background Modes > Remote notifications가 추가되어 있는지 확인해 주십시오.
    • aps-environment가 development인지 확인해 주십시오.
    • Unity는 빌드된 Xcode 프로젝트에서 확인해 주십시오.
  2. 대시보드의 프로젝트 설정 > 일반 메뉴에서 [화이트리스트] 버튼을 클릭해, 테스트 기기가 로그인하는 네트워크의 공인 IP를 개발 유형으로 등록하고 사용여부를 켜 주십시오.
    • 개발 유형은 IP 주소만 등록할 수 있습니다. Wi-Fi와 이동통신망은 IP가 다르므로 푸시 토큰이 등록되는 로그인 시점의 네트워크 IP를 등록해 주십시오.
    • 자세한 내용은 화이트리스트 사용 시 주의사항을 참조해 주십시오.
  3. 푸시 토큰이 SDK에 전달된 뒤 앱에서 로그인해 주십시오. 개발 화이트리스트에 등록된 IP로 로그인하면 같은 푸시 토큰이 일반(APNS)과 샌드박스(SANDBOX) 두 가지로 등록됩니다.
    • 화이트리스트는 로그인 시점에 확인하므로 먼저 등록한 뒤 로그인해 주십시오. 이미 로그인한 상태에서 등록했거나 토큰이 전달되기 전에 로그인했다면 로그아웃 후 다시 로그인해 주십시오.
  4. 대시보드의 운영 > 메시지 > 푸시 알림 메뉴에서 [샌드박스 디바이스] 버튼을 클릭해 테스트 사용자의 사용자 ID와 설명을 등록해 주십시오.
    • 샌드박스 푸시는 샌드박스 디바이스에 등록한 사용자에게만 발송되며, 최대 100개까지 등록할 수 있습니다.
  5. [추가] 버튼을 클릭해 푸시를 등록할 때 플랫폼을 샌드박스로 선택해 발송해 주십시오.
  6. 샌드박스 푸시가 수신되지 않으면 아래 TestFlight 또는 Ad Hoc 빌드 절차로 운영 환경에서 푸시 수신을 확인해 주십시오.

TestFlight, Ad Hoc 빌드(운영 환경) 테스트 절차

TestFlight 또는 Ad Hoc 빌드는 운영 환경의 푸시를 사용하므로 화이트리스트와 샌드박스 디바이스 등록 없이 일반 발송으로 테스트할 수 있습니다. 테스트하는 방법은 다음과 같습니다.

  1. 해당 빌드의 aps-environment가 production인지 확인해 주십시오.
  2. 앱에서 로그인한 후 운영 > 메시지 > 푸시 알림 메뉴에서 플랫폼을 iOS 또는 전체로 선택해 발송해 주십시오.
  3. 실제 사용자에게 발송되지 않도록 대상 국가 등 발송 조건을 제한해 주십시오.

문제 해결

자주 발생하는 오류와 해결 방법은 다음과 같습니다.

Q. java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process {패키지 이름}. Make sure to call FirebaseApp.initializeApp(Context) first.

A. 해당 오류는 gradle 파일에 푸시를 위한 설정이 누락된 경우입니다. 아래 사항을 확인해 주십시오.

프로젝트 최상단 build.gradle.kts를 확인해 주십시오.

  • Gradle (프로젝트 루트):
plugins {
    id("com.google.gms.google-services") version "4.4.1" apply false
}

앱 모듈의 build.gradle.kts를 확인해 주십시오.

  • Gradle (모듈: app):
plugins {
    id("com.google.gms.google-services")
}

Q. org.gradle.api.GradleException: File google-services.json is missing. The Google Services Plugin cannot function without it.

A. 해당 오류는 google-services.json 파일을 찾을 수 없는 경우 발생합니다. 해당 파일을 앱 모듈 루트 폴더에 올바르게 배치했는지 확인해 주십시오. (예시) ./project folder/app/google-services.json

Q. iOS 개발 빌드(Xcode 실행)에서 푸시가 오지 않습니다.

A. 개발 서명 빌드는 APNs 개발(sandbox) 환경 토큰을 사용합니다. 다음을 확인해 주십시오.

  • 앱의 aps-environment가 development이고 Push Notifications capability가 추가되어 있는지
  • 로그인하는 네트워크의 공인 IP가 프로젝트 설정 > 일반의 화이트리스트에 개발 유형으로 등록되어 있고 사용여부가 켜져 있는지(등록한 뒤 다시 로그인해야 반영됩니다)
  • 운영 > 메시지 > 푸시 알림의 샌드박스 디바이스에 사용자 ID가 등록되어 있고, 발송 시 플랫폼을 샌드박스로 선택했는지
  • 프로젝트 설정 > 연동 > Apple iOS (APNs) Configuration이 사용 상태이고 Key ID, Team ID, 번들 ID가 앱과 일치하는지
  • 위 항목을 확인했는데도 수신되지 않으면 TestFlight 또는 Ad Hoc 빌드로 운영 환경에서 푸시 수신을 확인해 주십시오. 자세한 절차는 iOS 개발 빌드(샌드박스) 푸시 테스트를 참조해 주십시오.

Q. 대시보드에서 APNs sandbox와 production 중 하나를 선택하는 설정이 있습니까?

A. 없습니다. APNs 설정에는 .p8 인증키, Key ID, Team ID, 번들 ID만 등록하며, 개발 환경 푸시는 개발 유형 화이트리스트와 샌드박스 디바이스 등록으로 구분합니다.

Q. TestFlight 빌드에서 푸시를 테스트하려면 화이트리스트가 필요합니까?

A. 필요하지 않습니다. TestFlight 빌드는 운영 APNs 환경을 사용하므로 플랫폼을 iOS 또는 전체로 선택해 일반 발송으로 테스트합니다.

Q. iOS 푸시 토큰은 FCM 토큰입니까?

A. 아닙니다. iOS는 FCM을 거치지 않고 APNs가 발급한 토큰을 사용합니다. 앱이 didRegisterForRemoteNotificationsWithDeviceToken에서 받은 값을 16진수 문자열로 변환해 NBase.setPushToken으로 전달해야 합니다. Android는 FCM 토큰을 사용합니다.

Q. 개발 빌드에서 TestFlight 빌드로 바꿨더니 푸시가 오지 않습니다.

A. 환경이 바뀌면 푸시 토큰도 새로 발급됩니다. 새 빌드에서 앱을 실행해 다시 로그인하여 새 토큰이 등록되도록 해 주십시오.

Q. 약관 동의창에서 푸시 동의를 받았는데 푸시가 오지 않습니다.

A. 사용자가 약관 동의창에서 푸시 항목을 체크하지 않으면 push, ad, night가 false로 저장됩니다. 푸시를 받으려면 푸시 상태 설정으로 값을 true로 변경해 주십시오. 약관 동의창에 푸시 항목이 표시되는 조건은 약관 동의창의 푸시 항목 표시 조건을 참조해 주십시오.