Maui

Getting Started with Localytics in Maui


This Maui NuGet simplifies the process of integrating Localytics into Maui iOS, Android projects.

The steps to integrate Localytics with this component mirrors the native Localytics SDK, so the following docs maybe helpful:

A sample project for using LocalyticsMaui NuGet is available in our Maui SDK Tester GitHub repository.

Getting Started

1. Install the SDK

  • Refer to the latest version of the Localytics Maui NuGet package on the NuGet Gallery.
  • For Maui single project type, you can install the SDK once for the whole project level, while for multi-project .net types, you need to install the SDK for each platform project.
  • Starting from LocalyticsMaui 1.0.8, targeting JDK 17 is required, which isn't downloaded by default for Visual Studio. You can edit the used JDK path from the Visual Studio settings.
screenshot of visual studio JDK path settings

2. Package Names

  • LocalyticsMaui.iOS - APIs available for use on the iOS platform iOS Localytics Docs
  • LocalyticsMaui.Android - APIs available for use on the Android platform Android Localytics Docs
  • LocalyticsMaui.Common - class available on both iOS and Android using .net dependencies only. The interfaces are the same across platforms offering similar functionality.

3. Platforms shared code

Add a file to your platforms shared code with the following contents

using LocalyticsMaui.Common;
# if __ANDROID__
using LocalyticsMaui.Android;
# else
using LocalyticsMaui.iOS;
# endif
namespace LocalyticsSample // Your project's namespace
{
public class LocalyticsMaui : LocalyticsSDK, ILocalytics, IPlatform
{
}
}

4. API Summary

APIs follow c# naming conventions and are a translation of the API on the native platform.

Common APIs

API Description
OpenSession Opens a session. Multiple calls are coalesed.
CloseSession Open sessions are marked with a pending close. Sessions are extended if there is Localytics activity before expiry of session timer.
Upload Uploads any data stored on the device by the Localytics SDK. Essential to do this early, to ensure upload completes before app is suspended.
PauseDataUploading All data upload is deferred until it is resumed. Calls to the upload API do not perform any action. When data upload is resumed, all locally stored data is immediately uploaded.
TagEvent Tags an event.
TagPurchased A standard event to tag a single item purchase event (after the action has occurred).
TagAddedToCart A standard event to tag the addition of a single item to a cart (after the action has occurred).
TagStartedCheckout A standard event to tag the start of the checkout process (after the action has occurred).
TagCompletedCheckout A standard event to tag the conclusions of the checkout process (after the action has occurred).
TagContentViewed A standard event to tag the viewing of content (after the action has occurred).
TagSearched A standard event to tag a search event (after the action has occurred).
TagShared A standard event to tag a share event (after the action has occurred).
TagContentRated A standard event to tag the rating of content (after the action has occurred).
TagCustomerRegistered A standard event to tag the registration of a user (after the action has occurred).
TagCustomerLoggedIn A standard event to tag the logging in of a user (after the action has occurred).
TagCustomerLoggedOut A standard event to tag the logging out of a user (after the action has occurred).
TagInvited A standard event to tag the invitation of a user (after the action has occurred).
TagScreen Allows tagging the flow of screens encountered during the session.
SetCustomDimension Sets the value of custom dimension, which is user-defined data. Customer-sensitive data should be hashed or encrypted.
GetCustomDimension Gets the custom value for a given dimension. Must not be called from the main thread.
SetIdentifier Sets the value of a custom identifier.
GetIdentifier Gets the identifier value for a given identifier. Must not be called from the main thread.
CustomerId CustomerId property representing a customer Id. Recommended to use SetCustomerId. For privacy, sensitive data should be hashed or encyrpted.
SetCustomerId Sets customer Id and privacy status automatically.
SetProfileAttribute Attribute values can be long, string, array of long or array of string.
AddProfileAttribute Adds values to a profile attribute that is a set.
RemoveProfileAttribute Removes values from a profile attribute that is a set.
IncrementProfileAttribute Increments the value of a profile attribute.
DecrementProfileAttribute Decrements the value of a profile attribute.
DeleteProfileAttribute Deletes a profile attribute.
SetCustomerEmail Convenience method to set a customer's email.
SetCustomerFirstName Convenience method to set a customer's first name.
SetCustomerLastName Convenience method to set a customer's last name.
SetCustomerFullName Convenience method to set a customer's full name.
SetOptions Customize the behavior of the SDK by setting custom values for various options.
SetOption Customize the behavior of the SDK by setting custom value for various options.
LoggingEnabled Property that controls if the Localytics SDK emits logging information.
OptedOut Controls collection of user data.
PrivacyOptedOut Opts out of data collection and requests a Delete data request to be submitted to the cloud service.
InstallId An installation identifier.
LibraryVersion Version of the Localytics SDK.
TestModeEnabled Controls the Test Mode characteristics of the Localytics SDK.
InAppAdIdParameterEnabled ADID parameter is added to In-App call to action URLs.
TriggerPlacesNotificationForCampaignId Triggers a places notification for the given campaignId and regionId.
InboxAdIdParameterEnabled ADID parameter is added to Inbox call to action URLs.
InAppMessageDismissButtonLocation Location of the dismiss button on an In-App msg.
SetInAppMessageDismissButtonHidden Dismisses button hidden state on an In-App message.
TriggerInAppMessage Triggers an In-App message.
TriggerInAppMessagesForSessionStart Triggers campaigns as if a Session Start event had just occurred.
DismissCurrentInAppMessage Dismisses a currently displayed In-App message.
InboxCampaigns An array of all Inbox campaigns that are enabled and can be displayed.
AllInboxCampaigns An array of all Inbox campaigns that are enabled.
RefreshInboxCampaigns Refreshes inbox campaigns from the Localytics server that are enabled and can be displayed.
RefreshAllInboxCampaigns Refreshes inbox campaigns from the Localytics server that are enabled.
TagImpression A standard event to tag an In-App impression.
SetInboxCampaign Sets an Inbox campaign as read.
InboxListItemTapped Tells the Localytics SDK that an Inbox campaign was tapped in the list view.
InboxCampaignsUnreadCount Sets an Inbox campaign as read.
SetLocationMonitoringEnabled Sets an Inbox campaign as read.
PushTokenInfo Returns a string version of Push Token on all platforms.

5. Dictionaries

Customer Properties Dictionary

Dictionary Key Name Value Description
customerId Customer Id.
firstName First name of the customer.
lastName Last name of the customer.
fullName Full name of the customer.
emailAddress Email address of the customer.

This dictionary can be passed to TagCustomerLoggedIn and TagCustomerRegistered API.

6. Events

Events are available as static events in the LocalyticsSDK class in the Localytics.Shared namespace.

Event Args for events common to both Android and iOS share an interface and can be implemented in a Shared PCL project.

Event Name Args Description
LocalyticsDidTagEvent LocalyticsDidTagEventEventArgs Fired when an analytics event is tagged.
LocalyticsSessionWillClose None When Session is closed.
LocalyticsSessionDidOpen LocalyticsSessionDidOpenEventArgs When session is opened.
LocalyticsSessionWillOpen LocalyticsSessionWillOpenEventArgs When session will be opened.
LocalyticsDidTriggerRegions LocalyticsDidTriggerRegionsEventArgs When a Geo fence is triggered for a region.
LocalyticsDidUpdateLocation LocalyticsDidUpdateLocationEventArgs When a new location update is received.
LocalyticsDidUpdateMonitoredGeofences LocalyticsDidUpdateMonitoredGeofencesEventArgs When geofences that are being monitored are changed due to a change in campaign or a significant location change.
InAppDidDisplayEvent InAppDidDisplayEventArgs When an In-App is displayed.
InAppWillDismissEvent InAppWillDismissEventArgs When an In-App will be dismissed.
InAppDidDismissEvent InAppDidDismissEventArgs When an In-App is dismissed.

IOS Specific Events

Event Name Args Description
RequestAlwaysAuthorization CLLocationManager Action that is invoked when a request for Always Authorization for Location is necessary.
RequestWhenInUseAuthorization CLLocationManager Action that is invoked when a request for When In Use Authorization for Location is necessary.

Events Args

LocalyticsDidTagEventEventArgs

EventName - string identifying the type of the event.
Attributes - a dictionary identifying the attributes attached to the event
CustomerValue - a nullable double that identifies any provided customer value when tagging the event

LocalyticsSessionDidOpenEventArgs

isFirst - bool identifying if this is the first session
isUpgrade - bool identifying if this session open is following an upgrade
isResume - bool identifying if this is a session that is being resumed.

LocalyticsSessionWillOpenEventArgs

Provides same as properties as LocalyticsSessionDidOpenEventArgs

LocalyticsDidTriggerRegionsEventArgs

Regions providing an array of regions and is of type LLRegion[].
RegionEvent of type LLRegionEvent identifying the trigger event type 'Enter' or 'Exit'.

LocalyticsDidUpdateLocationEventArgs

iOS
Location - CLLocation type which reports the current location.

LocalyticsDidUpdateMonitoredGeofencesEventArgs

AddedRegions and RemovedRegions are additional properties. They are both of type LLRegion[]. AddedRegions provides the array of new regions added. RemovedRegions provides an array of regions that were removed from monitoring.

InAppDidDisplayEventArgs, InAppWillDismissEventArgs, InAppDidDismissEventArgs

These do not define any additional properties other than those in EventArgs and are placeholders for future to minimize signature changes.

DidOptOutEventArgs

The properties are

  • Current OptOut status (bool)
  • Campaign

7. Delegates

Delegate Name Args Return Description
InAppDelaySessionStartMessagesDelegate None bool Delays display of Session Start InApps to allow for launch screen and other page transitions including login to complete.
InAppShouldShowDelegate InAppCamaign bool Determines if an InApp should be displayed. Default is true, when a delegate is not specified.
ShouldDeepLinkDelegate string (absolute url) bool Used to determine if the absolute url specified as a string should be displayed by Localytics SDK.
InAppWillDisplayDelegate InAppCampaign, InAppConfiguration InAppConfiguration Modified InAppConfiguration that is to be used to display the InApp specified by InAppCampaign.
PlacesShouldDisplayCampaignDelegate PlacesCampaign bool Determines if a Places Campaign should be displayed.
LocalyticsShouldDeeplink deeplink (url string), Campaign bool Determines if Localytics should deep link. When false, the application handles any necessary deep link url.
LocalyticsShouldPromptForLocationPermissions Campaign bool Determines if there should be a delegate/event to request permissions for location, notifications etc.
LocalyticsShouldDeeplinkToSettings Intent, Campaign bool Determines if the Localytics SDK should deep link to system settings.

8. Android Versions

Type Version
Minimum Android version API Level 21
Target Android version API Level 33
Target framework Android 13.0

9. iOS Versions

  • Minimum deployment target is iOS 8.0
  • CoreLocation - Required for location services. Requires implementing the request for Location Permissions in the App

10. iOS-Specific Platform Code

In order to use the LocalyticsMaui.iOS API in a source file, you will need to add the namespace LocalyticsMaui.iOS. Before calling anything else on the Localytics API, override the FinishedLaunching in your app delegate to integrate with your Localytics App Key.

Note: it's not recommended to use the AutoIntegrate function as it's not fully supported since .net6

using LocalyticsMaui.iOS;
...
namespace LocalyticsSample;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
...

public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
{
...
// Localytics Integrate
Localytics.LoggingEnabled = true;
Localytics.Integrate("b70c948d304fc756d8b6e63-ecd3437a-a073-11e6-c6e3-008d99911bee", launchOptions ?? new
NSDictionary());

// Register for remote notifications
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());

UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();

return base.FinishedLaunching(uiApplication, launchOptions);
}

protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}

Usage

You can use the Localytics API by calling the class methods/accessors of Localytics or LocalyticsSDK. Here's a sample of some of the calls.

LocalyticsSDK localytics = LocalyticsSDK.SharedInstance;
localytics.SetOption("ll_session_timeout_seconds", 10);
localytics.CustomerId = "Sample Customer";

localytics.SetProfileAttribute("Sample Attribute", LocalyticsMaui.Common.XFLLProfileScope.Application, 83);
localytics.AddProfileAttribute("Sample Set", LocalyticsMaui.Common.XFLLProfileScope.Organization, new long[] {
321, 654 });

localytics.TagEvent("Test Event");
localytics.TagScreen("Test Screen");

localytics.Upload();

The above samples only demonstrate the syntax of calling the LocalyticsMaui.iOS API. For more information about how to use Localytics, see iOS Localytics Docs.

Push and In-App Messaging

  1. Enable background modes
  2. Register for remote notifications
  3. Add the following in your main AppDelegate inside FinishedLaunching where the Integrate call is

    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
    UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |
    UIUserNotificationTypeSound);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
    }
    else
    {
    [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |
    UIRemoteNotificationTypeSound)];
    }
    
  4. Receiving Notification in the foreground when the application is in the foreground, DidReceiveRemoteNotification override in the Application is invoked when a notification is received.
  5. NSDictionary apsDict = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
    // apsDict[new NSString("alert")] returns the message.
    // Present the notification using a UIAlert.
    

    WillFinishLaunching or FinishedLaunching override provide the dictionary when the notification was received in the background.

11. Android-Specific Platform Code

In order to use the LocaluticsMaui.Android API in a source file, you will need to add the namespace LocalyticsMaui.Android. Before calling anything else on the Localytics API, you will need:

  1. Call one of the Integrate methods Integrate or AutoIntegrate within your custom Application class
  2. using Android.App;
    using Android.Runtime;
    using LocalyticsMaui.Android;
    namespace LocalyticsSample;
    
    [Application]
    public class MainApplication : MauiApplication
    {
    public MainApplication(IntPtr handle, JniHandleOwnership ownership)
    : base(handle, ownership)
    {
    }
    
    override public void OnCreate()
    {
    base.OnCreate();
    
    #if DEBUG
    var localytics = LocalyticsMauiShared.SharedInstance;
    localytics.LoggingEnabled = true;
    #endif
    
    Localytics.AutoIntegrate(this);
    
    }
    
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
    }
    
  3. Modify the AndroidManifest.xml to add App Key, receivers and permissions.
  4. <application android:label="LocalyticsSample" android:icon="@drawable/icon">
        <meta-data android:name="LOCALYTICS_APP_KEY"
            android:value="xxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
        <receiver android:name="com.localytics.android.ReferralReceiver" android:exported="true">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    

    Manifest merging is not supported with Maui. Therefore, all AndroidManifest.xml entries need to be made manually. Follow instructions for manual integration.

  5. Configure required parameters using localytics.xml or through setting options. Add a localytics.xml in Resources/values. For a sample refer here.

Usage

You can use the Localytics API by calling the class methods/accessors of Localytics or LocalyticsSDK. Here's a sample of some of the calls.

LocalyticsSDK localytics = LocalyticsSDK.SharedInstance;
localytics.SetOption("ll_session_timeout_seconds", 10);
localytics.CustomerId = "Sample Customer";

localytics.SetProfileAttribute("Sample Attribute", LocalyticsMaui.Common.XFLLProfileScope.Application, 83);
localytics.AddProfileAttribute("Sample Set", LocalyticsMaui.Common.XFLLProfileScope.Organization, new long[] {
321, 654 });

localytics.TagEvent("Test Event");
localytics.TagScreen("Test Screen");

localytics.Upload();

The above samples only demonstrate the syntax of calling the LocalyticsMaui.Android API. For more information about how to use Localytics, see Android Localytics Docs.

Push and In-App Messaging

  1. Check for Play Services Availability as described in FCM Notifications Walkthrough.
  2. The Localytics Native SDK Push Integration can be used to integrate push.
  3. Maui has limited support for manifest merging. The changes are best done directly in AndoidManifest.xml.