PushizoDocs
SDK guides

.NET MAUI SDK

Pushizo.Maui — a .NET MAUI package (net8.0/net9.0) wrapping the native Android and iOS SDKs over a JSON bridge; push, in-app, notification inbox, preferences.

Pushizo.Maui 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 plugin (with C# naming). Namespace PushizoSdk.Maui. Example: examples/maui-app.

TargetBehavior
net8.0-android, net9.0-androidNative Android SDK (minSdk 23)
net8.0-ios, net9.0-iosNative iOS SDK (iOS 15+)
Others (Windows, MacCatalyst)Calls are no-ops and a warning is logged once; the notification inbox and preferences return PLATFORM_NOT_SUPPORTED (Pushizo.IsSupported)

Installation

dotnet add package Pushizo.Maui
// MauiProgram.cs
using PushizoSdk.Maui;

var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>()
       .UsePushizo("app_…", o =>
       {
           o.ApiUrl = "https://api.pushizo.com";
           o.RequiresPrivacyConsent = false;   // if true, no network calls until SetConsentGiven(true)
           o.LogLevel = LogLevel.Warn;
           // Android: AndroidDefaultChannelId, AndroidDefaultChannelName · iOS: IosAppGroup, IosApnsEnvironment, IosProvisionalAuthorization
       });

Instead of UsePushizo you can also call Pushizo.Initialize("app_…", new PushizoOptions { … }) directly. Calling it again with the same App ID is a no-op; a different App ID throws InvalidOperationException. Calls made before Initialize throw InvalidOperationException.

Android

  1. Download google-services.json from the Firebase console and add it to the project:
<ItemGroup Condition="$(TargetFramework.Contains('-android'))">
  <GoogleServicesJson Include="Platforms/Android/google-services.json" />
</ItemGroup>
  1. Dashboard → Channels → Android Push → Firebase service account JSON.
  2. POST_NOTIFICATIONS, the FCM service and the notification Activity are merged from the native SDK manifest.
  3. UsePushizo picks up the permission result automatically from the lifecycle event. If you only use Pushizo.Initialize, add this in MainActivity:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    PushizoAndroid.OnRequestPermissionsResult(requestCode);
}

iOS

  1. aps-environment in Platforms/iOS/Entitlements.plist, and UIBackgroundModes → remote-notification in Info.plist.
  2. Dashboard → Channels → iOS Push → .p8 key.
  3. The native SDK doesn't use swizzling; forward the APNs token from AppDelegate:
[Export("application:didRegisterForRemoteNotificationsWithDeviceToken:")]
public void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) =>
    PushizoIos.RegisteredForRemoteNotifications(deviceToken);

[Export("application:didFailToRegisterForRemoteNotificationsWithError:")]
public void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) =>
    PushizoIos.FailedToRegisterForRemoteNotifications(error);
  1. For rich media, badges and delivery confirmation, add a Notification Service Extension target in Xcode and use the PushizoNotificationServiceExtension class from the native PushizoExtension (SPM) or Pushizo/Extension (CocoaPods); use IosAppGroup for badge sharing. Details: iOS SDK.

Permission

bool granted = await Pushizo.Notifications.RequestPermissionAsync(fallbackToSettings: true); // opens settings if denied
bool current = Pushizo.Notifications.Permission;
Pushizo.Notifications.PermissionChanged += (_, e) => Console.WriteLine(e.Permission);

PermissionChanged comes from the native SDK's permission observer and fires only on an actual change. Without permission the subscription stays pending; it is registered automatically once permission is granted.

User, subscription, tags and aliases

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

Pushizo.User.AddTag("plan", "pro");
Pushizo.User.AddTags(new Dictionary<string, string> { ["plan"] = "pro", ["city"] = "istanbul" });
Pushizo.User.RemoveTag("plan");                                 // RemoveTags(new[] { "plan", "city" })
IReadOnlyDictionary<string, string> 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 (PushSubscriptionState)
sub.OptIn(); sub.OptOut();
sub.Changed += (_, e) => Console.WriteLine($"{e.Previous.Id} → {e.Current.Id}");

Email and SMS

Pushizo.User.AddEmail("Ali@Pushizo.com");       // → ali@pushizo.com; ArgumentException if invalid
Pushizo.User.RemoveEmail("ali@pushizo.com");
Pushizo.User.AddSms("+905321234567");           // expects E.164; ArgumentException if invalid
Pushizo.User.RemoveSms("+905321234567");
IReadOnlyList<string> emails = Pushizo.User.Emails; // SmsNumbers: addresses registered on this device

User preferences

UserPreferences prefs = await Pushizo.User.GetPreferencesAsync();   // prefs.Preferences, prefs.Categories
foreach (var category in prefs.Categories)
    Console.WriteLine($"{category.Key}: {category.LocalizedName("en")} (default {category.DefaultOptedIn})");

UserPreferences updated = 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). UserPreference: Category, Channel, OptedIn, Explicit, Source, UpdatedAt (DateTimeOffset?). Category model: Preferences.

Notification events

Pushizo.Notifications.Clicked += (_, e) => Navigate(e.Url);        // e.Notification, e.ActionId, e.Url
Pushizo.Notifications.ForegroundWillDisplay += (_, e) =>
{
    if (IsChatOpen) e.PreventDefault();   // synchronous inside the handler; 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. PushizoNotification: Title, Body, ImageUrl, Url, DeliveryId, MessageId, Actions, Data. Events fire on the native SDK's thread; use MainThread.BeginInvokeOnMainThread for UI updates.

In-app messages

Pushizo.InAppMessages.AddTrigger("level", "gold");    // AddTriggers(dict), RemoveTrigger(s), ClearTriggers(), GetTriggers()
Pushizo.InAppMessages.SetScreen("cart");             // in the page's OnAppearing; SetScreen(null) when leaving
Pushizo.Session.SendEvent("cart_viewed");
Pushizo.InAppMessages.Paused = true;
Pushizo.InAppMessages.Clicked += (_, e) => Console.WriteLine($"{e.MessageId} {e.ActionId} {e.Url}");
Pushizo.InAppMessages.DidDisplay += (_, e) => Console.WriteLine(e.Message.Id); // WillDisplay, WillDismiss, DidDismiss

Messages are rendered with native UI (Android Dialog, iOS UIWindow). Trigger keys are 1-64 characters and values at most 200 characters.

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();

limit is 1-200 (ArgumentOutOfRangeException if out of range). Times are DateTimeOffset?.

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. Android only: on the iOS, Windows and MacCatalyst targets 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 a profile, ads consent, badge and location permissions

These calls from the native Android and iOS SDKs are available in the bridge as well; the ones that exist on a single platform do nothing on the other one and never throw.

// Login with a profile: email, SMS, tags and aliases in one call; an invalid field throws ArgumentException and no login happens.
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 the advertising ID (GAID / IDFA; the app obtains 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: deletes the record on the server

// Badge (on Android the count is stored and written to later notifications)
Pushizo.Notifications.SetBadgeCount(3);
Pushizo.Notifications.ClearBadge();

// Location permission state and the background ("always") permission
bool foreground = Pushizo.Location.PermissionGranted;
bool background = Pushizo.Location.BackgroundPermissionGranted;
bool granted = await Pushizo.Location.RequestBackgroundPermissionAsync("To let you know when you arrive at the store.");

Pushizo.User.RegisterAdm(admRegistrationId);          // Fire OS ADM (Android only)
bool listening = await Pushizo.Chat.IsListeningAsync();
  • Login(externalId, profile, identityHash, jwt): the profile login of the native SDK is called on both platforms (Android HsUserProfile, iOS HSUserProfile); the profile and the proof are validated before the login and the fields are written after it. The identity proof is the same as for the other Login.
  • SetAdsPersonalizationConsentAsync returns the current preferences; false withdraws the consent. The advertising ID reaches an ad audience only for users with this consent, and only as a SHA-256 hash. The SDK ships no ad library and shows no ATT prompt.
  • SetBadgeCount throws ArgumentOutOfRangeException for a negative value. Android has no standard API for the launcher badge, so the count is stored in the native SDK and written to the notifications shown from then on (launchers that show a number, Android 8 and later); the badge is not visible while the tray is empty.
  • Location.PermissionGranted and BackgroundPermissionGranted are read from the native SDK on both platforms.
  • RequestBackgroundPermissionAsync(rationale) and RequestAlwaysPermissionAsync() ask for the same permission: on Android a rationale dialog and the ACCESS_BACKGROUND_LOCATION prompt (the Settings screen on Android 11 and later; false if the manifest lacks the permission), on iOS the "always" permission (requires NSLocationAlwaysAndWhenInUseUsageDescription; the rationale text is not used). The foreground permission must be granted first with RequestPermissionAsync.
  • RegisterAdm does nothing on iOS. On the Windows and MacCatalyst targets these calls do nothing, permission reads and requests return false, and the consent calls fail with the same PLATFORM_NOT_SUPPORTED error as preferences.

User property, observers, event ID and the ready-made chat screen

// User property: text, number, bool, list or dictionary; null deletes the property
Pushizo.User.SetProperty("plan", "pro");
Pushizo.User.SetProperty("interests", new[] { "sports", "music" });
Pushizo.User.SetProperty("plan", null);

// Observers: subscribe with +=, remove with -=
Pushizo.FeatureFlags.Changed += (_, _) => ApplyFlags();                    // values were refreshed from the server
Pushizo.Inbox.Changed += (_, e) => SetInboxBadge(e.UnreadCount);           // e.Type, e.ItemId, e.UnreadCount

// Event deduplication ID (8-64 characters; letters, digits and . _ : -)
Pushizo.Session.SendEvent("purchase", new Dictionary<string, object?> { ["sku"] = "A1" }, 129.9, "order_2024-0001");

// Badge result and current count
bool shown = Pushizo.Notifications.TrySetBadgeCount(3);
int badge = Pushizo.Notifications.BadgeCount;

// Ready-made chat screen
Pushizo.Chat.Show();
bool open = Pushizo.Chat.IsPresented;
bool closed = Pushizo.Chat.Hide();
  • User.SetProperty(key, value): the key is trimmed; an empty key, a key longer than 64 characters or an unsupported value throws ArgumentException. The value can be text, a number, bool, a date, Guid, an enum, a dictionary or a list (up to 16 levels); dictionaries and lists cannot contain null. While offline the call waits in the native queue.
  • FeatureFlags.Changed: raised when the flag values are refreshed from the server successfully (session start and RefreshAsync); read the current values with IsEnabled / GetValue.
  • Inbox.Changed: InboxChangeType.Read, ReadAll and Archived are reported on every operation, Listed and Count only when the unread count changes. ItemId is set only for Read and Archived events.
  • Both events are raised on the main thread of the native SDK; an exception in one handler does not block the others.
  • Session.SendEvent(name, properties, value, eventId): if the same ID is sent again (or an ad pixel / Conversions API uses the same ID) the server records the event once. For an empty or malformed ID the native SDK generates its own; nothing is thrown. The three-parameter SendEvent is unchanged.
  • Notifications.TrySetBadgeCount(count) does the same as SetBadgeCount and returns the result: true on iOS; on Android true when the count was stored and the badge can be shown on this device (false before Android 8, when notifications are off or when the channel badge is disabled; the count is stored anyway). BadgeCount returns the last stored count on Android and the app icon badge on iOS.
  • Chat.Show() opens the ready-made chat screen of the native SDK (Android HsChatActivity, iOS modal HSChatViewController); if the screen is already open it is not opened again. Chat.Hide() returns true when a screen was open. Chat.IsPresented reports the real state on both platforms (on Android the bridge tracks the screen through the Activity lifecycle).
  • On the Windows and MacCatalyst targets SetProperty, SendEvent and Chat.Show do nothing; TrySetBadgeCount, Chat.Hide and Chat.IsPresented return false, BadgeCount returns 0, and the events are never raised.

Events (outcomes) and more

Pushizo.Session.SendEvent("purchase", new Dictionary<string, object?> { ["sku"] = "A1" }, value: 129.9);
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

Error codes

Notification inbox and preference errors come with PushizoException.Code:

CodeMeaning
NOT_READYThe subscription/user registration hasn't completed yet.
INVALID_ARGUMENTThe native SDK rejected the input.
PLATFORM_NOT_SUPPORTEDA target other than Android/iOS (Windows, MacCatalyst).
INVALID_RESPONSEThe bridge response couldn't be parsed.
HS_…Server error code; catalog: Errors.

Validation errors on the C# side (ArgumentException, ArgumentOutOfRangeException) are thrown before reaching the bridge.

Testing

# Shared layer + unit tests (no workload required)
dotnet test sdk/maui/tests/Pushizo.Maui.Tests -p:PushizoIncludeAndroid=false
# Android (maui-android workload, JDK 17, ANDROID_HOME, gradle 8.x on PATH)
dotnet build sdk/maui/src/Pushizo.Maui -f net9.0-android
# iOS (macOS + Xcode 15+ + maui-ios workload)
dotnet build sdk/maui/src/Pushizo.Maui -f net9.0-ios

Troubleshooting

SymptomCause / fix
InvalidOperationException: Önce Pushizo.Initialize çağrılmalı ("Pushizo.Initialize must be called first")The SDK was used before UsePushizo/Initialize was called.
Permission result doesn't arrive on AndroidInitialize is used instead of UsePushizo and PushizoAndroid.OnRequestPermissionsResult isn't forwarded.
No subscription created on iOSPushizoIos.RegisteredForRemoteNotifications isn't called in AppDelegate, or aps-environment is missing.
UI error in an event handlerEvents arrive on a native thread; use MainThread.BeginInvokeOnMainThread.
"Ambiguity" Kotlin error in the Android buildStale build/native Gradle cache; delete it and rebuild.
RequestPermissionAsync always falsePermission denied on Android 13+ (fallbackToSettings: true); Push capability missing on iOS. Other symptoms: Android, iOS.

On this page