> For the complete documentation index, see [llms.txt](https://docs.gamepot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gamepot.io/basics/gamepot-3.0/images-and-media/editor/push.md).

# PUSH

Push notifications allow developers to send reliable and efficient messages from servers or the cloud to mobile devices.\
By using push, you can send notification messages (messages that the system displays to the user) and data messages (key-value pairs of data that the app processes) to mobile apps and web apps. Push notifications support a variety of platforms, including iOS, Android, and web applications.

{% hint style="info" %}
Starting from May 15, 2024, Firebase Cloud Messaging (FCM) will expire tokens on Android devices that have been inactive for more than 270 days. If your account is affected, the number of subscription cancellations may increase.
{% endhint %}

## Key Features

* **Variety of Message Types:** You can send various types of messages, including notification messages and data messages.
* **Mass Messaging:** Push notifications allow you to send messages to millions of users simultaneously, enabling efficient messaging in large-scale applications.
* **Cross-Platform Support:** Messages can be received on various platforms, including iOS, Android, and web applications.
* **Advanced Messaging Options:** Offers advanced features like setting message priorities, message lifespan, topic-based subscriptions, and conditional message delivery.

## How to Use Push Notifications (Mobile) <a href="#undefined" id="undefined"></a>

1. **Set Up Firebase Project**
   * Create a project in the Firebase Console (console.firebase.google.com).
   * Add an application (Android or iOS) to the created project.
   * Download the necessary Firebase configuration files (google-services.json or GoogleService-Info.plist) and add them to the Gamepot Dashboard under settings.
2. **Add FCM SDK**
   * For Android, add the necessary definitions in the build.gradle.kts files for both the app module and project module.

     ```Kotlin
     // (Module : app) build.gradle.kts
     plugins {
     ...
        id("com.google.gms.google-services")
     }

     dependencies {
     ...
        implementation("com.google.firebase:firebase-messaging-ktx:23.2.1")
     }
     ```

     <br>

     ```Kotlin
     // (Module : project)의 build.gradle.kts
     plugins {
        ...
        id("com.google.gms.google-services") version "4.3.15" apply false
     }
     ```
   * iOS의 경우, CocoaPods을 사용하여 `Firebase/Messaging` pod를 설치합니다.
3. **Requesting Permission for Push Notifications (iOS)**
   * For iOS apps, you must request permission from the user to allow push notifications. This can be done using `UNUserNotificationCenter`.
4. Device Token Registration and Message Reception
   * When the app is installed and launched, the FCM SDK generates a unique token for the app instance. This token can be registered on the server to send messages to specific devices.
   * To receive messages, implement a listener in the application.

By using FCM, you can enhance user engagement, deliver critical information quickly, and build a customized notification system that supports a variety of messaging scenarios. FCM provides developers with a variety of tools and APIs to easily integrate and manage cloud messaging.

## Add Code to Set Up Push <a href="#unity" id="unity"></a>

{% tabs %}
{% tab title="Kotlin" %}
No additional actions are required to use push notifications.
{% endtab %}

{% tab title="iOS" %}
Add the code below to AppDelegate.

```swift
import NBase

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // 푸시 사용여부 퍼미션 허가 요청
    registerForRemoteNotifications()
    return true
}
func registerForRemoteNotifications() {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) 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) {
    // 푸시 알림 등록에 실패했습니다. 오류: \(error.localizedDescription)
    NBase.setPushToken(token: "")
}
```

{% endtab %}

{% tab title="Unity" %}
Please check 'Use Notification' in Tools -> GamePotSDK -> Edit Settings.

![](/files/WRzsJhmP26VgCNtnt6Wk)&#x20;
{% endtab %}
{% endtabs %}

## Change Push Status

* To change the push notification receipt settings, please call the code below.

{% tabs %}
{% tab title="C#" %}

```csharp
NBaseSDK.NBase.setPushState(enable, night, ad, token, (pushState, error) => {
    if (error != null)
    {
        // failed.
        // Display the message using error.message.
    }
    else
    {
        // succeeded.
    }
});
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val pushToken = NBase.getPushToken()
val pushState = com.nbase.sdk.model.PushState(
    enable = enable,
    night = night,
    ad = ad,
    token = pushToken
)
NBase.setPushState(pushState) { status, e ->
    if (error != null) {
        // failed.
        // Display the message using error.message.
    } else {
        // succeeded.
    }
};
```

{% endtab %}

{% tab title="Java" %}

```java
String pushToken = _NBase.getPushToken();
com.nbase.sdk.model.PushState pushState = new com.nbase.sdk.model.PushState(
        Boolean.parseBoolean(enable),
        Boolean.parseBoolean(night),
        Boolean.parseBoolean(ad),
        pushToken
);
NBase nBase = NBase.INSTANCE;
nBase.setPushState(pushState, (status, e) -> {
    if (e != null) {
        // failed.
        // Display the message using e.getMessage.
    } else {
        // succeeded.
    }
    return null;
});
```

{% endtab %}

{% tab title="Swift" %}

```swift
NBase.setPushState(enable: enable, ad: ad, night: night, token: NBase.getPushToken()) { result in
    switch result {
    case .success(let data):
        // succeeded.
    case .failure(let error):
        // failed.
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
[NBaseBridge.shared setPushState:enable night:night ad:ad token:token :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // failed.
        // Display the message using error.localizedDescription.
    } else {
        // succeeded.
    }
}];
```

{% endtab %}
{% endtabs %}

* To check the push notification receipt settings, please call the code below.

{% tabs %}
{% tab title="C#" %}

```csharp
NBaseSDK.NBase.getPushState((pushState, error) => {
    if (error != null)
    {
        // failed.
        // Display the message using error.message.
    }
    else
    {
        // succeeded.
    }
});
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
NBase.getPushState() { state, e ->
    if (error != null) {
        // failed.
        // Display the message using error.message.
    } else {
        // succeeded.
    }
};
```

{% endtab %}

{% tab title="Java" %}

```java
NBase nBase = NBase.INSTANCE;
nBase.getPushState((state, e) -> {
    if (e != null) {
        // failed.
        // Display the message using e.getMessage.
    } else {
        // succeeded.
    }
    return null;
});
```

{% endtab %}

{% tab title="Swift" %}

```swift
NBase.getPushState() { result in
    switch result {
    case .success(let data):
        // succeeded.
    case .failure(let error):
        // failed.
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
[NBaseBridge.shared getPushState:^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // failed.
        // Display the message using error.localizedDescription.
    } else {
        // succeeded.
    }
}];
```

{% endtab %}
{% endtabs %}

## How to Test Push Notifications (Mobile) <a href="#undefined" id="undefined"></a>

Push notifications can be tested in three ways:

1. To verify via the dashboard: Go to Dashboard -> Member List -> Member Details (More Info) Click the Send Push button to send a push notification to the specific member.<br>

   <figure><img src="/files/5jLSp2Hc8Bq5vkpUTIdi" alt=""><figcaption></figcaption></figure>
2. How to Test in the Firebase Console (AOS)\
   In the Firebase Console, select your project, go to **Messaging**, and in the **Campaigns** section, click the **New Campaign** button to test message sending.<br>

   <figure><img src="/files/KmQndndv3aKJVvy7HLJu" alt=""><figcaption></figcaption></figure>

   <figure><img src="/files/1ANjgGdxxBmCu7xrPG0u" alt=""><figcaption></figcaption></figure>

Copy and paste the token retrieved from the app, click the **+** button to input the token, and then press the **Test** button to complete the process. You can verify if the message is sent to the specified token.

3. (iOS) How to Test in the CloudKit Console\
   Go to the [**CloudKit Console**](https://developer.apple.com/icloud/cloudkit/), navigate to **Push Notifications**, and create a new notification.

<figure><img src="/files/ernObRwo8sQ6ypmJSQYm" alt=""><figcaption></figcaption></figure>

After entering the **Device Token** and **Payload**, you can verify if the message is successfully sent to the specified token.

## Troubleshooting <a href="#undefined" id="undefined"></a>

Q. java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.nbase.main. Make sure to call FirebaseApp.initializeApp(Context) first.

A. **A.** This error occurs when push notification settings are missing in the `gradle` file. Please check the following: `build.gradle.kts` at the top level of your project.

```xml
plugins {
   id("com.google.gms.google-services") version "4.4.1" apply false
}
```

Add it to the build.gradle.kts file within the app directory.

```xml
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. This error occurs when the `google-services.json` file cannot be found. Please ensure that the file is correctly placed in the root folder of the module: app level.\
**Example:** `./project folder/app/google-services.json`
