PushizoDocs
SDK guides

Unity SDK

com.pushizo.unity — a UPM package (Unity 2021.3+) wrapping the native Android and iOS SDKs; push, in-app, notification inbox, preferences, automatic iOS/Android build settings.

com.pushizo.unity wraps the native Pushizo Android (com.pushizo:pushizo-android) and iOS (Pushizo Swift) SDKs; trigger evaluation, the offline queue, delivery feedback and in-app rendering live in the native SDK. The surface is the same as the legacy provider's v5 and the Flutter and .NET MAUI SDKs. Namespace PushizoSdk. Example: the in-package Demo sample (Samples~/Demo).

PlatformBehavior
Android device (minSdk 23)Native Android SDK; Java bridge in Runtime/Plugins/Android
iOS device (iOS 15+)Native iOS SDK; Swift bridge in Runtime/Plugins/iOS ([DllImport("__Internal")])
Unity Editor, Standalone, WebGLNo network calls or push; calls are logged, tags/triggers/emails are kept in memory, the notification inbox and preferences return PLATFORM_NOT_SUPPORTED (Pushizo.IsSupported is false)

Requirements: Unity 2021.3+, External Dependency Manager for Unity (EDM4U) (Android Gradle and iOS CocoaPods dependencies), CocoaPods for iOS.

Installation

Packages/manifest.json (or Window → Package Manager → + → Add package from git URL):

{
  "dependencies": {
    "com.pushizo.unity": "https://github.com/pushizo/pushizo-unity.git#0.1.0"
  }
}

Project Settings → Pushizo: App ID, API URL (for the iOS Notification Service Extension), APNs environment (development/production), App Group, NSE target on/off and the google-services.json path. The settings are written to Assets/Pushizo/PushizoSettings.asset and used by post-build steps; at runtime the SDK is still initialized with Pushizo.Initialize.

Android

  1. Download google-services.json from the Firebase console and put it at Assets/google-services.json. During the build, the Firebase values (google_app_id, gcm_defaultSenderId, google_api_key, project_id) are written to the unityLibrary resources; the Firebase Unity SDK is not required.
  2. Dashboard → Channels → Android Push → Firebase service account JSON.
  3. Player Settings → Minimum API Level 23. The POST_NOTIFICATIONS permission and the FCM service are merged from the native SDK manifest.
  4. Gradle dependencies are resolved with EDM4U (Editor/PushizoDependencies.xml: native SDK, Kotlin stdlib, AndroidX Core). Until the native SDK is published to Maven Central, run gradle -p sdk/android :pushizo:publishToMavenLocal and add the mavenLocal() repository in Player Settings → Publishing Settings → Custom Main Gradle / Settings Template.

iOS

The post-build step (Editor/PushizoIosPostProcessor.cs) automatically adds:

  • the Push Notifications capability (aps-environment) and Background Modes → Remote notifications,
  • an optional App Group,
  • build settings for the Swift bridge (SWIFT_VERSION, embedding the Swift runtime),
  • Classes/Preprocessor.h → UNITY_USES_REMOTE_NOTIFICATIONS 1 (Unity only enables this when its own notification APIs are used; while it is off, UnityAppController doesn't receive the APNs token or forward it to the bridge),
  • the PushizoNotificationServiceExtension target (rich media, badges, delivery confirmation) and the Pushizo/Extension pod in the Podfile (EDM4U generates the Podfile at 40, the plugin runs at 45, pod install at 50).

The APNs token is taken from Unity's UnityAppController notifications; no AppDelegate changes are needed. In Xcode, select the signing team for both targets (automatic if Player Settings → iOS → Signing Team ID is set). Dashboard → Channels → iOS Push → .p8 key. Until the native SDK is published to CocoaPods, use pod 'Pushizo/App', :path => '<repo>/sdk/ios' in the generated Podfile (Pushizo/Extension in the NSE target). NSE details: iOS SDK.

Initialization

using System.Collections.Generic;
using PushizoSdk;
using UnityEngine;

public class PushizoBootstrap : MonoBehaviour
{
    private void Awake()
    {
        Pushizo.Initialize("app_…", new PushizoOptions
        {
            ApiUrl = "https://api.pushizo.com",
            RequiresPrivacyConsent = false,   // if true, no network calls until SetConsentGiven(true)
            LogLevel = LogLevel.Warn,
            // Android: AndroidDefaultChannelId, AndroidDefaultChannelName · iOS: IosAppGroup, IosApnsEnvironment, IosProvisionalAuthorization
        });
        Pushizo.Notifications.Clicked += e => Debug.Log($"Clicked: {e.Url}");
    }
}

Call Initialize once from the main thread at app startup; calling it again with the same App ID is a no-op, and a different App ID throws InvalidOperationException. All events and Task results are delivered on the Unity main thread (via a hidden PushizoDispatcher object).

Permission

bool granted = await Pushizo.Notifications.RequestPermissionAsync(fallbackToSettings: true); // opens settings on permanent denial
bool current = Pushizo.Notifications.Permission;
Pushizo.Notifications.PermissionChanged += granted => Debug.Log(granted);  // from the native permission observer, only on an actual change

User, subscription, tags and aliases

Pushizo.SetConsentGiven(true);                      // false: clears the queue and the local identity
Pushizo.Login("user_42", identityHash);            // the hash is required if identity verification is on
Pushizo.Logout();

Pushizo.User.AddTag("level", "12");
Pushizo.User.AddTags(new Dictionary<string, string> { ["level"] = "12", ["clan"] = "red" });
Pushizo.User.RemoveTag("level");                   // RemoveTags(new[] { "level", "clan" })
var tags = Pushizo.User.GetTags();
Pushizo.User.SetLanguage("tr");
Pushizo.User.AddAlias("crm_id", "42");             // AddAliases(dict), RemoveAlias("crm_id")
string? externalId = Pushizo.User.ExternalId; string? hsId = Pushizo.User.Id;

var sub = Pushizo.User.PushSubscription;           // Id, Token, OptedIn, Current
sub.OptIn(); sub.OptOut();
sub.Changed += e => Debug.Log($"{e.Previous.Id} → {e.Current.Id}");

Email and SMS

Pushizo.User.AddEmail("ali@pushizo.com");          // ArgumentException if invalid
Pushizo.User.RemoveEmail("ali@pushizo.com");
Pushizo.User.AddSms("+905321234567");              // expects E.164
Pushizo.User.RemoveSms("+905321234567");
var emails = Pushizo.User.Emails;                  // SmsNumbers

User preferences

UserPreferences prefs = await Pushizo.User.GetPreferencesAsync();   // prefs.Preferences, prefs.Categories
foreach (var category in prefs.Categories) Debug.Log(category.LocalizedName("en"));
await Pushizo.User.SetPreferencesAsync(new[]
{
    new PreferenceInput("promo", optedIn: false),                   // channel null = all channels
    new PreferenceInput("news", optedIn: true, channel: "email"),   // ios_push | android_push | web_push | email | sms
});

SetPreferencesAsync validates input before it crosses the bridge (1-100 records, category 1-64 characters, a known channel or null); invalid input throws ArgumentException. If there is no subscription yet you get a PushizoException (NOT_READY); in the Editor, PLATFORM_NOT_SUPPORTED. Category model: Preferences.

Notification events

Pushizo.Notifications.Clicked += e => OpenScreen(e.Url);            // e.Notification, e.ActionId, e.Url
Pushizo.Notifications.ForegroundWillDisplay += e =>
{
    if (inBattle) e.PreventDefault();   // call e.Display() later if needed
};

When the app is opened from a notification and there is no Clicked subscriber yet, the last tap is stored and delivered to the first subscriber. While a ForegroundWillDisplay subscriber exists, native display is deferred; if the handlers don't call PreventDefault(), the notification is shown (on iOS the decision must be made within 25 s). PushizoNotification: Title, Body, ImageUrl, Url, DeliveryId, MessageId, Actions, Data.

In-app messages

Pushizo.InAppMessages.AddTrigger("level", "gold");   // AddTriggers(dict), RemoveTrigger(s), ClearTriggers(), GetTriggers()
Pushizo.InAppMessages.SetScreen("shop");             // SetScreen(null) when leaving the scene
Pushizo.InAppMessages.Paused = true;                 // don't show during cutscenes/gameplay
Pushizo.InAppMessages.Clicked += e => Debug.Log($"{e.MessageId} {e.ActionId} {e.Url}");
Pushizo.InAppMessages.DidDisplay += e => Debug.Log(e.Message.Id); // WillDisplay, WillDismiss, DidDismiss

Messages are rendered with native UI (Android Dialog, iOS UIWindow) on top of the Unity view.

Notification inbox

InboxPage page = await Pushizo.Inbox.ListAsync(limit: 20, cursor: null); // Items, UnreadCount, NextCursor, HasMore
InboxItem item = await Pushizo.Inbox.MarkReadAsync(page.Items[0].Id);
int remaining = await Pushizo.Inbox.MarkAllReadAsync();
await Pushizo.Inbox.ArchiveAsync(item.Id);
int unread = await Pushizo.Inbox.UnreadCountAsync();

Content cards

ContentCardFeed feed = await Pushizo.ContentCards.ListAsync(limit: 20); // Cards, UnviewedCount
await Pushizo.ContentCards.LogImpressionAsync(feed.Cards[0].Id);
await Pushizo.ContentCards.LogClickAsync(id);   // click (also counts as an impression)
await Pushizo.ContentCards.DismissAsync(id);    // removes it from the feed

Cards do not appear in the notification inbox; the feed is ordered pinned → priority → newest. limit is 1-100 (default 50). A registered subscription and user are required (otherwise NOT_READY). Log an impression when a card is shown and a click when it is tapped; the stats appear on the campaign detail page.

Android delivery hardening

On vendors such as Xiaomi, Huawei, Oppo, Vivo and Samsung, the battery and auto-start manager stops apps in the background, so notifications arrive late or not at all. Pushizo.Delivery reads the restrictions on the device and takes the user to the relevant settings screen. Details: Android delivery hardening.

DeliveryStatus status = Pushizo.Delivery.GetStatus(); // Supported, Vendor, Rom, Risk, Restricted, RecommendedSettings
if (Pushizo.Delivery.ShouldShowGuidance())            // at risk and the dialog was not shown in the last 14 days
{
    bool opened = await Pushizo.Delivery.ShowGuidanceAsync(); // ready-made dialog (22 languages); opens the settings screen if accepted
}
Pushizo.Delivery.OpenSettings(DeliverySetting.AutoStart);     // from your own UI

DeliveryRisk: None, Elevated, High. DeliverySetting: Auto, Notifications, AutoStart, BatteryOptimization, AppDetails. ShouldShowGuidance(30) changes the interval and ShowGuidanceAsync(setting, message) the screen and the text; the SDK never shows the dialog on its own. Effective only in Android device builds: on iOS, in the Editor and before Initialize the status is DeliveryStatus.Unsupported (Risk is None), and OpenSettings and ShowGuidanceAsync return false without doing anything; the calls never throw.

Login with profile, ads consent, badge and background location permission

// Login + profile in one call; an invalid email/phone throws ArgumentException before the login.
Pushizo.Login("user_42", new PushizoUserProfile
{
    Email = "ali@example.com",
    Sms = "+905321234567",
    Tags = new Dictionary<string, string> { ["plan"] = "pro" },
    Aliases = new Dictionary<string, string> { ["crm_id"] = "42" },
}, jwt: token);

// Ads personalization consent and advertising ID (GAID / IDFA after the ATT prompt; the game reads the ID).
UserPreferences prefs = await Pushizo.User.SetAdsPersonalizationConsentAsync(true);
IReadOnlyList<UserConsent> consents = await Pushizo.User.GetConsentsAsync(); // Purpose, Granted, Source, UpdatedAt
Pushizo.Ads.SetAdvertisingId(advertisingId);   // null: the server-side record is deleted

Pushizo.Notifications.SetBadgeCount(3);        // iOS badge; stored on Android and written to later notifications
Pushizo.Notifications.ClearBadge();

// Location permission state and background ("always") permission: for geofencing.
bool foreground = Pushizo.Location.PermissionGranted;
bool background = Pushizo.Location.BackgroundPermissionGranted;
bool granted = await Pushizo.Location.RequestBackgroundPermissionAsync("We notify you when you are near a store.");

bool listening = await Pushizo.Chat.IsListeningAsync();
Pushizo.User.RegisterAdm(admRegistrationId);   // Fire OS ADM; no-op on iOS

RequestBackgroundPermissionAsync and RequestAlwaysPermissionAsync request the same permission: on Android a rationale dialog followed by ACCESS_BACKGROUND_LOCATION (the system Settings screen on Android 11 and later; false when the manifest lacks the permission), on iOS the "always" permission (NSLocationAlwaysAndWhenInUseUsageDescription is required, the rationale text is not used). Foreground location permission must be granted first. The consent calls use the preferences endpoint: a registered subscription is required (NOT_READY otherwise) and the Editor returns PLATFORM_NOT_SUPPORTED. Single-platform calls are no-ops on the other platform and in the Editor and never throw: RegisterAdm on iOS; in the Editor the badge is a no-op and the permission states and IsListeningAsync return false.

User property, event id, observers and the built-in chat screen

// User property: string, number, bool, list or dictionary; null deletes the property.
Pushizo.User.SetProperty("plan", "pro");
Pushizo.User.SetProperty("favorites", new List<object> { "sword", "shield" });
Pushizo.User.SetProperty("plan", null);

// Event id: pass the same id as your ad pixel and the server records the event once.
Pushizo.Session.SendEvent("purchase", new Dictionary<string, object> { ["sku"] = "gems_100" }, 4.99, "order-2026-0001");

// Observers (on the main thread).
Pushizo.FeatureFlags.Changed += () => ApplyFlags();                    // values were refreshed from the server
Pushizo.Inbox.Changed += e => SetBadge(e.UnreadCount);                 // e.Type, e.ItemId, e.UnreadCount

// Badge: on Android the count is stored and written to later notifications.
bool shown = Pushizo.Notifications.TrySetBadgeCount(3);                // can this device show the badge
int stored = Pushizo.Notifications.BadgeCount;                         // stored count on Android; 0 on iOS

// Built-in chat screen (native UI on top of the game).
Pushizo.Chat.Show();
bool open = Pushizo.Chat.IsPresented;
bool closed = Pushizo.Chat.Hide();                                     // true when an open screen was closed
  • The SetProperty key is 1-64 characters; the value can be a string, number, bool, date, Guid, enum, list or dictionary (null is not allowed inside a list or dictionary). An invalid key or value throws ArgumentException before reaching the bridge; the operation waits in the native queue while offline.
  • SendEvent(name, properties, value, eventId) is an overload added next to the existing three-parameter call. The id is 8-64 characters (letters, digits and . _ : -); when it is empty or malformed the native SDK generates its own id.
  • FeatureFlags.Changed fires after a successful refresh at session start and after RefreshAsync. Inbox.Changed types are InboxChangeType: Listed, Read, ReadAll, Archived, Count; read, read-all and archive are reported on every operation, list and count only when the unread count changes. ItemId is set only for Read and Archived.
  • The badge is now backed by the native SDK on Android as well: the launcher badge is derived from notifications, so the count is stored and written to later notifications (Android 8 and later; no badge is shown while the tray is empty). TrySetBadgeCount returns false on Android when the badge cannot be shown (before Android 8, notifications or the channel badge turned off) and true on iOS; SetBadgeCount does the same work without returning the result. BadgeCount is the stored count on Android; it returns 0 on iOS because the native iOS SDK does not expose the badge for reading.
  • Chat.Show() opens the HsChatActivity activity on Android and the modal HSChatViewController screen on iOS; calling it again while the screen is open does not open a second one. IsPresented is the native value on iOS; on Android the native SDK does not expose this state, so the bridge tracks the chat activity lifecycle. Use the Chat data calls to draw your own UI.
  • On iOS, login with profile and the location permission state are now native SDK calls (Pushizo.login(_:profile:…), Pushizo.Location.permissionGranted); the C# behavior and error format are unchanged.
  • In the Editor these calls never throw: SetProperty, SendEvent and Chat.Show are logged, TrySetBadgeCount, Chat.Hide and IsPresented return false, BadgeCount returns 0, and no observer events are raised.

Events (outcomes) and more

Pushizo.Session.SendEvent("purchase", new Dictionary<string, object> { ["sku"] = "gems_100" }, value: 4.99);
Pushizo.Notifications.ClearAll();           // this app's notifications (also resets the badge on iOS)
Pushizo.Notifications.RemoveGroupedNotifications("orders");                // Android android_group / iOS thread-id
Pushizo.Notifications.RemoveNotification(n.AndroidNotificationId!.Value);  // Android tray ID (null on iOS)
Pushizo.Notifications.RemoveNotification("request-id");                    // iOS: UNNotificationRequest.identifier
Pushizo.Debug.SetLogLevel(LogLevel.Debug);  // None | Error | Warn | Info | Debug

Pushizo.Debug is the SDK's manager; use the fully qualified name if needed to avoid confusion with UnityEngine.Debug.

Error codes

Notification inbox and preference errors carry PushizoException.Code:

CodeMeaning
NOT_READYThe subscription/user registration hasn't completed yet.
INVALID_ARGUMENTThe native SDK rejected the input.
PLATFORM_NOT_SUPPORTEDEditor, Standalone or WebGL.
INVALID_RESPONSEThe bridge response couldn't be parsed.
HS_…Server error code; catalog: Errors.

Validation errors on the C# side (ArgumentException) are thrown before reaching the bridge; calls made before Initialize throw InvalidOperationException.

Testing and sample

# Editor-less core (managed layer)
cd sdk/unity/Validation~ && dotnet test Pushizo.Unity.Validation.sln
# Real Unity Editor (EditMode tests + Windows/Android/iOS target builds)
powershell -ExecutionPolicy Bypass -File sdk/unity/TestProject~/run-tests.ps1

For EditMode tests in your own project, add "testables": ["com.pushizo.unity"] to Packages/manifest.json and use Window → General → Test Runner. Sample: Package Manager → Pushizo → Samples → Demo → Import; in an empty scene, add the PushizoDemo component to a GameObject and enter your App ID and API URL.

Troubleshooting

SymptomCause / fix
No push in the EditorExpected behavior: there is no native SDK in Editor/Standalone/WebGL; test on a device.
Android: google_app_id missing / no tokengoogle-services.json is not at the path set in Project Settings → Pushizo.
Android: pushizo-android can't be resolvedEDM4U isn't installed, Force Resolve wasn't run, or mavenLocal() wasn't added.
iOS: Pushizo module not foundEDM4U's pod install didn't run; open the .xcworkspace instead of the .xcodeproj in Xcode.
iOS: NSE signing errorSelect the signing team for the NSE target too (or set the Signing Team ID).
RequestPermissionAsync always falsePermission denied on Android 13+ (fallbackToSettings: true); Push capability missing on iOS. Other symptoms: Android, iOS.

On this page