Skip to content

GetSocial Notifications on Unity

Prerequisite

Setup Unity Push Notifications

Android

GetSocial supports sending push notifications via Firebase Cloud Messaging (FCM) or Google Cloud Messaging (GCM). If you’ve already have a Push Notifications set up in your project, skip the Step 1.

  1. Add the Firebase to your app following the official guide.

    • Import the FirebaseInstanceId.unitypackage to your Unity project.
  2. Login to the GetSocial Dashboard.

  3. Go to the “App settings” section → “Notifications” tab.
  4. Enable Android notifications by clicking on the switch and fill in “API Key” and “Sender ID” values.

    You can find “API Key” (Server key) and “Sender ID” in your application settings in Firebase developer console.

    GetSocial Dashboard - Enable Push Notifications

  5. Select what kind of notifications users will receive:

    GetSocial Dashboard - Notifications Type

  6. Press “Save” button in the bottom right corner.

  7. In your Unity project. Go to menu bar → GetSocial → Edit Settings.
  8. In Android Settings section ensure that push notifications are enabled:

    Setup Push Notifications iOS in Unity Editor

  9. Check notifications texts and translations.

    GetSocial Dashboard - Check Notification Text

  10. Check setup sending a test notification to your test device.

    GetSocial Dashboard - Send Test Notification

iOS

Generate Push Notification Certificate

  1. Open Apple Developer Portal;

  2. Log into your account;

  3. Open “Certificates, Identifiers & Profiles”;

  4. Find “App IDs” in “Identifiers” section and find your application;

  5. Click “Edit” and scroll to “Push Notifications” configurations;

  6. Click “Create Certificate…” for Development and Production.

  7. Follow the instructions how to create the certificate and download it.

Export Server .p12 Certificate

Double click on downloaded .cer file (your certificate), it will add it to your Keychain Access and open. Click on “Certificates” section, find your certification, and export it with clicking “Export Apple Development/Production iOS Push Services”, create a password for your certificate and save it somewhere on the disk.
Do it for both Production and Development certificates.

Adding push notification configs to the dashboard

  1. Login to the GetSocial Dashboard.
  2. Go to the “App settings” section → “Notifications” tab.
  3. Enable iOS notifications by clicking on the switch and upload certificates, downloaded in the previous section.

  4. Select what kind of notifications users will receive:

    GetSocial Dashboard - Notifications Type

  5. Select “Sandbox” if your application is using development push notifications or “Production” for development.

  6. Press “Save” button in the bottom right corner.

  7. In your Unity project. Go to menu bar → GetSocial → Edit Settings.

  8. In iOS Settings section ensure that push notifications are enabled and push notifications environment is correct:

    Setup Push Notifications iOS in Unity Editor

  9. Check notifications texts and translations.

  10. Check setup sending a test notification to your test device.

Enable/disable GetSocial Notifications on the Client Side

By default GetSocial SDK automatically registers itself for push notifications during initialization. To prevent this behavior, follow next steps:

  1. Open your “Unity Editor”.

  2. Find GetSocialEdit Settings in menu.

  3. In General Settings find Push Notification and disable Register Automatically checkbox.

Setup Push Notifications in Unity Editor

In this case, GetSocial will not automatically register your device on our Push Server. But you still can register for push notifications manually:

1
GetSocial.RegisterForPushNotification();

Handle Click on Push Notifications

GetSocial UI

If you are using GetSocial UI, our respective view will be opened on click on push notifications: if someone liked your activity or commented under your activity, this activity will be shown on application start.

Important

If GetSocial View is opened automatically by GetSocial UI, you can not set the custom title, UiActionListener, action button handler, etc. In this case, we recommend you to override the default behavior and open GetSocial View by yourself.

Notification Listener

To handle notification click in your code, we provide NotificationListener, you can set it in Awake method of your MonoBehaviour derived class.

1
2
3
4
5
6
7
8
GetSocial.SetNotificationListener (notification, wasClicked => {
    if (!wasClicked)
    {
        return false;
    }
    bool isHandled = processNotification(notification);
    return isHandled;
});

wasClicked parameter is true when the application was opened by push notification click or false if the application was in the foreground when the notification was received.
You return a bool: true if notification is handled by your own, or false if not, so it will be handled by our library.
For example, if you want to prevent of showing GetSocial Activity Feed UI on notification click:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
bool ProcessNotification(Notification notification) {
    switch (notification.Action) {
        case Notification.Type.OpenActivity:
            // add custom logic here
            Debug.Log ("Activity action received");
            return true;

        default:
            return false;
    }
}

In this case, you’re showing something you would want to show about the activity, and GetSocial UI will not be shown.

Tip

If you are not using GetSocial UI, we recommend to handle notifications by yourself - better user experience would be to react to notification actions.

Show Notifications In Foreground

By default, when your application is in foreground, GetSocial notifications are not shown. Instead, NotificationListener is called. To show notifications while application is in foreground, follow next steps:

  1. Open your “Unity Editor”.

  2. Find GetSocialEdit Settings in menu.

  3. In General Settings find Push Notification and enable Foreground Notifications checkbox.

If Foreground Notifications is checked:

  • Notifications will be shown when your application is in foreground.
  • NotificationListener will be called after clicking on the notification; parameter wasClicked will be true.

iOS 9 and lower

“Foreground Notifications” works on iOS 10+ only, on the older version of iOS the notification will be delegated to the NotificationListener.

Get Notifications

To be sure your users didn’t miss any important(or not) notifications, you can query GetSocial notifications and show it to your user inside the app. Or send it once again as local notification. Or handle it in any other convenience method.

Query

You have two types of queries: NotificationQuery and NotificationsCountQuery to get notifications list and notifications count respectively.

Notification can differ by a read status - be read or unread. Also each notification has type, it is one of Notification.NotificationTypes constants.

To query notifications by a read status, use one of static factory methods Read(), Unread() or ReadAndUnread().

By default notifications of all types are queries. Also you can explicitly call OfAllTypes() to be sure that all types are queries. To specify a list of types you’re interested in call method OfTypes(Notification.NotificationTypes... types) and pass one or few types you want to query.

Notifications Count

To get the count of notifications use GetSocial.User.GetNotificationsCount(query, onSuccess, onFailure) method. For example, to get a number of all unread notifications for current user:

1
2
NotificationsCountQuery query = NotificationsCountQuery.Unread().OfAllTypes();
GetSocial.User.GetNotificationsCount(query, count => Debug.Log("Notifications count is" + count), error => Debug.LogError("Failed to get notifications count: " + error));

Notifications List

Similar to notifications count you can fetch a list of notifications using GetSocial.User.getNotifications(query, callback) mehtod:

1
2
NotificationsQuery query = NotificationsQuery.Unread().OfAllTypes();
GetSocial.User.GetNotifications(query, notifications => ShowNotifications(notifications), error => Debug.LogError("Failed to get notifications: " + error));

Read And Unread Notifications

All the notifications that are sent to a user are unread. The only exception is notifications that was clicked by a user - such becomes read automatically.

If you want to set notification read or unread use GetSocial.User.SetNotificationsRead(notificationIds, isRead, onSuccess, onFailure) method:

1
2
3
4
List<Notification> notificationsToBeRead = ...;
var notificationIds = notificationsToBeRead.ConvertAll(notification => notification.Id);
bool markAsRead = true;
GetSocial.User.SetNotificationsRead(notificationIds, markAsRead, () => Debug.Log("Successfully changed notification status"), error => Debug.LogError("Failed to change notifications: " + error));

You can mark just one notification using new List<string> { notification.Id }.

Disable Push Notifications For User

If you don’t want to send notifications to a user, use GetSocial.User.SetPushNotificationsEnabled(false, onSuccess, onFailure). Notifications will still appear in the notification center. To enable it back use GetSocial.User.setPushNotificationsEnabled(true, onSuccess, onFailure).

To check current setting value use GetSocial.User.IsPushNotificationsEnabled(onSuccess, onFailure).

Send Notification

You can also send notifications directly from the SDK to other users just in few lines of code:

1
2
3
4
string text = string.Format("Hello, {0}! Greetings from {1}.", SendNotificationPlaceholders.CustomText.ReceiverDisplayName, SendNotificationPlaceholders.CustomText.SenderDisplayName);
NotificationContent notification = NotificationContent.NotificationWithText(text).WithTitle("Greetings!");
List<string> receivers = new List<string> { SendNotificationPlaceholders.Receivers.ReferredUsers, SendNotificationPlaceholders.Receivers.Referrer };
GetSocial.User.SendNotification(receivers, notification, summary => Debug.Log("Sent " + summary.SuccessfullySentCount + " notifications"), error => Debug.LogError("Failed to send notifications: " + error));

This example shows how to send message with dynamic text and title to all the users, whom you invited and the one who invited you.

Receivers

  • Receivers list can not be empty.
  • It may contain up to 25 different user IDs and one or many placeholders from SendNotificationPlaceholders.Receivers.
  • If you will send more that 25 user IDs - method will fail and no notifications will be sent.
  • If you mentioned one user twice or user is in two or more placeholder groups - the notification will be sent only once.
  • If our service can not send the notification to one or many users, it will be delivered to all other users. You can check the number of successfully sent notifications in the response.

Notification Content

There are three ways to create a notification content:

  • Dynamically create all the content on the SDK.
  • Use one of the GetSocial templates and override template placeholders.
  • Create your own template and override template placeholders.

Tip

You still can override any content when using the template notification.

  • To create a notification with text use NotificationContent.NotificationWithText(String text).
  • Add a title using notification.WithTitle(title) method.
  • You can add one or few default placeholders from the SendNotificationPlaceholders.CustomText to both title and text.

Template Notification

To create a template for notifications:

  1. Login to the GetSocial Dashboard.

  2. Go to the “Notifications” section → “Templates” tab.

  3. Press “New Template” button.

    GetSocial Dashboard - Create New Template

  4. Create a new template by giving a unique name and meaningful description.

  5. Setup the notification content. You can add translations, emojis, default placeholders(Sender/Receiver display name) or custom placeholders that can be replaced on the SDK. Also you can set the fallback value for each placeholder which will be taken if it wasn’t sent from the SDK side.

  6. To check the list of your custom templates switch to “Custom” tab using radio button.

Now create and setup notification using GetSocial iOS SDK:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Text for the template "new_level_achieved" on the Dashboard:
// "Your friend [SENDER_DISPLAY_NAME] just reached [USER_LEVEL] lvl! Try to beat his score!"

NotificationContent notification = NotificationContent.NotificationFromTemplate("new_level_achieved");
... // set up your notification
notification.AddTemplatePlaceholder("USER_LEVEL", "7"); // add replacement for your placeholders without brackets

GetSocial.User.SendNotification(users, notification, onSuccess, onError);
// Your recipients will receive text:
// "Your friend John Doe just reached 7 lvl! Try to beat his score!"

[SENDER_DISPLAY_NAME] is automatically replaced with sender display name.

Action

To set an action to the notification click, use notification.WithAction(Notification.Type action). By default it is Notification.ActionType.Custom.

Add action data using AddActionData(string key, string val) or AddActionData(Dictionary<string, string> dictionary) - second one will add all the keys and values from parameter map. For the default GetSocial actions use one of Notification.Key constants to guarantee the default behaviour. Also you can pass any custom data you want and handle it on the receiver side.

You can send any of predefined actions that will be handled by the SDK, for example to open Activity Feed with id “funny-stories” use:

1
2
3
NotificationContent notification = NotificationContent.NotificationWithText("Hey, join the channel with funny stories and tell yours!")
    .WithAction(Notification.ActionType.OPEN_ACTIVITY)
    .AddActionData(Notification.Key.OpenActivity.FEED_NAME, "funny-stories");

You can send custom action with custom action data and handle it by your own using Notification Listener.

GetSocial Actions

  1. Open User Profile.

    Notification.ActionType.OpenProfile is not handled by SDK but you can handle it with Notification Listener. Parameters:

    • Notification.OpenProfile.UserId - GetSocial user ID whose profile should be opened.
  2. Open Activity Feed.

    Notification.ActionType.OpenActivity is handled by SDK. Will open activity feed with provided name, or activity feed post itself or scroll to the certain comment if provided. Parameters:

    • Notification.OpenActivity.ActivityId - Activity Feed post ID.
    • Notification.OpenActivity.CommentId - Comment under that activity. Optional.

    or:

    • Notification.OpenActivity.FeedName - Feed to Open. Use ActivitiesQuery.GlobalFeed to open global feed.
  3. Open Smart Invites.

    Notification.ActionType.OpenInvites is handled by SDK. Will open Smart Invites screen. Has no required parameters.

  4. Open URL.

    Notification.ActionType.OpenUrl is handled by SDK. Wil open a system web browser with provided URL. Parameters:

    • Notification.OpenUrl.Url - URL to open.

Customize Notification Icon (Android only)

By default, GetSocial SDK will use application icon as the notification icon.

There are two ways to customize the icon. First option is to put image with name getsocial_notification_icon into Assets/Plugins/Android/res/drawable/ folder.

Notification icons with Gradle build

If you’re using Gradle build system in your Build Settings for Android, you have to pack your resources to .aar file and place it under Assets/Plugins/Android.

If you want to use an existing icon for notifications, you can set the resource name in the Android Manifest. For instance to use ic_notification_custom.png from Assets/Plugins/Android/res/drawable/:

1
2
3
4
5
6
7
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.NotificationIcon"
        android:resource="@drawable/ic_notification_custom" />
    ...
</application>

As a result all notifications coming from GetSocial SDK will use custom icon:

Customized Notification Icon

Also, you can customize large notification icon using manifest. To use ic_large_notification_icon.png from Assets/Plugins/Android/res/drawable:

1
2
3
4
5
6
7
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.LargeNotificationIcon"
        android:resource="@drawable/ic_large_notification_icon" />
    ...
</application>

Customized Notification Icon

Correct file path and name

You should put the correct name of drawable in your AndroidManifest.xml! If your image is named my_custom_image.png, than your android:resource value should be @drawable/my_custom_image without extension.

Customize Notifications Channel (Android only)

All GetSocial notifications come to separate notifications channel with ID getsocial_channel_id. By default, channel is called Social and has empty description. Name is localized to all GetSocial supported languages.

To customize channel name or description, add the following meta data pointing to the string resource to AndroidManifest.xml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.NotificationsChannelTitle"
        android:resource="@string/getsocial_notifications_channel_title" />

    <meta-data
        android:name="im.getsocial.sdk.NotificationsChannelDescription"
        android:resource="@string/getsocial_notifications_channel_description" />
    ...
</application>

To check your customization, on your phone (Android O, API 26 and higher) go to SettingsApps and Notifications[YOUR APP NAME]Notifications and find your channel. Description can be checked after pressing the channel name at the bottom of the screen.

Next Steps

Give us your feedback! Was this article helpful?

😀 🙁