Xamarin Guide

iOS Integration

Install

This SDK is distributed via the public NuGet gallery: https://www.nuget.org/packages/GrowSDK.Xamarin/.

If you have both an iOS and an Android project, you should add the NuGet package to each following the Xamarin Add Package dialog. See here for a detailed walkthrough on using NuGet with a Xamarin project.

Install-Package GrowSDK.Xamarin -Version 0.0.0

Requirement

iOS version > 11.0

Now open your’s AppDelegate class file and import the GrowSDK library.1using GrowSDK.Xamarin.Initialization

using GrowSDK.Xamarin.Initialization

Xcode Signing & Capabilities

Making the SDK fully functional requires the developer to configure capabilities on the application target and the extension target.

1. Push Notifications

This capability needs to be added to the application target. And to add it, you need to select your application target and then select the option Signing & Capabilities. From there, tap on the button +Capability.


On the prompt, you search for Push Notifications and add this capability. The capability should now be on your application target.

2. Background Modes

Allow the SDK to prepare, and process content in the background requires adding background mode on the application side. To do this, you need to select your application target and then select the option Signing & Capabilities.

From there, tap on the button +Capability. On the prompt, you search for Background Modes and add this capability.

On the Background Modes section of the target, you need to enable Background to fetch, Remote notifications, Background processing.

3. App Group

This capability needs to be added to both targets, application, and extension. To do that, you select the target and then choose the option Signing & Capabilities. From there, tap on the button +Capability. Then on the prompt, you search for App Group and add this capability.


On the App Group section of the target, you tap on the [ + ] to add a new container.

A prompt is displayed, and on that, you type the name you want to use. This name will be the one you need to pass on the configs.appGroup of the Grow SDK configuration object.

If you have an auto signing, Xcode will update the profiles automatically; if not, you need to access the Apple Certificates website and update them with this new capability.

You can now repeat these steps with the same App Group name on your Extension target.

4. Keychain sharing

This capability allows the SDK to share the same Device Id across different applications of the same owner. And as well, if configured on the application side, it must be configured on the extension side.
Select your application target and then choose the option Signing & Capabilities to add this capability. From there, tap on the button +Capability. Then on the prompt, you search for Keychain sharing and add this capability.

On the Keychain Sharing section of the target, you tap on the [ + ] to add a new container and type the name you want to use. This name will be the one you need to pass on the configs.keychainGroupName of the Grow SDK configuration object.


You can repeat these steps with the same Keychain Group Name on your Extension target.

Configuration

To configure the SDK, it is required an API Key provided by the platform and the [App Group] configured on your Xcode project.

App group is required to keep campaign features fully functional.

If you want to use and share the same Device Id on each of your applications, you can also provide a [Keychain Group Name].

Now open your’s AppDelegate class file and import the GrowSDK framework.

GrowSDK.Xamarin.Initialization

In the same file, find the method application(_:didFinishLaunchingWithOptions:) and, on it, create a Configuration object from the GrowSDK framework. This object receives a lambda function to provide the possible configurations to be used to initialize SDK.

GrowConfiguration myConfiguration = new GrowConfiguration((obj) 
            =>    {obj.apiKey = "(API_Key)";  
                  obj.appGroup = "(App_Group_Name)";
                  obj.keychainGroupName = "(Team_Id).(Keychain_Group_Name)";});

Grow.Start(myConfiguration, options);

Setup the SDK on the Extension

  1. To handle Grow Push campaigns, you must add a Notification Service Extension to your app:Create a new target for Notification Service Extension with File > New > Target > Search Notification Service Extension, then Next.
    Give a name, then Finish.
  2. Then go to your project configuration and select your Extension Target. From the Frameworks and Libraries, and open NotificationService.cs and import the GrowSDK library:
using GrowSDK.Xamarin.NotificationService;

This extension should extend our class instead of the Apple UNNotificationServiceExtension configuration(). So, your extension class must look like this:

namespace Sample.NotificationExtension
{
    [Register("NotificationService")]
    public class NotificationService : UNNotificationServiceExtension
    {
        Action<UNNotificationContent> ContentHandler { get; set; }
        UNMutableNotificationContent BestAttemptContent { get; set; }
        GrowNotificationService GrowNotificationService { get; set; }

        protected NotificationService(IntPtr handle) : base(handle)
        {
            // Note: this .ctor should not contain any initialization logic.
        }

        public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
        {
            ContentHandler = contentHandler;
            BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();

            // Modify the notification content here...
            BestAttemptContent.Title = $"{BestAttemptContent.Title}[modified]";

            GrowExtensionConfiguration myExtensionConfiguration = new GrowExtensionConfiguration((obj) =>
            {
                obj.apiKey = "(API_Key)";
                obj.appGroup = "(App_Group_Name)";
                obj.keychainGroupName = "(Team_Id).(Keychain_Group_Name)";
            });

            GrowNotificationService = GrowNotificationService.DidRecieve(request, myExtensionConfiguration, (newContent) => {
                ContentHandler(newContent);
            });
        }

        public override void TimeWillExpire()
        {
            // Called just before the extension will be terminated by the system.
            // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.

            GrowNotificationService.ServiceExtensionTimeWillExpire();

            ContentHandler(BestAttemptContent);
        }
    }
}

Firebase

If you haven’t done so yet, you will need to register your project to Firebase. To do so, follow the instructions from the official Firebase Documentation.

On the prompt with choosing Firebase libraries, you must choose Firebase App Distribution and Firebase Crashlytics.

Android Integration

Install

This SDK is distributed via the public NuGet gallery: https://www.nuget.org/packages/GrowSDK.Xamarin/.

If you have both an iOS and an Android project, you should add the NuGet package to each following the Xamarin Add Package dialog. See here for a detailed walkthrough on using NuGet with a Xamarin project.

Install-Package GrowSDK.Xamarin -Version 0.0.0

Requirement

Android version > 10.0

Configuration

Right click on the android project > Add > New file to create a new class MyApplication.cs.
In your MyApplication.cs you should inherit from Application:

using GrowSDK.Xamarin.Initialization;

...

Context context = Android.App.Application.Context;

GrowConfiguration myConfiguration = new GrowConfiguration((obj) => {
    obj.apiKey = "(API_Key)";
});

Grow.Start(context, myConfiguration);

Change AndroidManifest.xml. Your application tag AndroidManifest.xml has to look like this:

<application android:label="@string/app_name" android:theme="@style/MainTheme" android:name=".MyApplication" android:usesCleartextTraffic="true">
    <activity android:name=".MainActivity"></activity>
</application>

Configure push notifications

If you haven’t done so yet, you will need to register your project to Firebase. To do so, follow the instructions from the official Firebase Documentation.

In your Android project add the Xamarin.Firebase.Messaging NuGet package.

Then create a class which inherit FirebaseMessagingService and override onMessageReceived and onNewToken methods. So, your class must looks like:

using Android.App;
using Firebase.Messaging;
using GrowSDK.Xamarin.FirebaseService;

namespace Sample.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class FirebaseService : FirebaseMessagingService
    {
        public override void OnNewToken(string p0)
        {
            base.OnNewToken(p0);
            Grow.Device.SetFirebasePushToken(token: p0);
        }

        public override void OnMessageReceived(RemoteMessage p0)
        {
            base.OnMessageReceived(p0);
            Grow.Compaign.processFirebaseMessage(message: p0);
        }
    }
}

Add the service previously created to the AndroidManifest inside your <application> tag. Make sure to set android:name to the relative path to your service:

<service
    android:name=".FirebaseService"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
     </intent-filter>
</service>

Enabling analytics

For reporting activity logs from the tagging plan (User Identifier, Attributes & Events), analytics must be enabled in the SDK.
By default, analytics are disabled, and can be turned on by changing the analytics state of the SDK.

This to enable analytics, please refer to this paragraph of SDK General Usage Guide

Integration Troubleshooting

1. No data in the GROW UI

If you notice your some dashboard cards related to app activity are not populated despite the fact you made some sessions:

  • Double check you are testing the correct app
  • Verify the device is opt-in analytics (Usage Guide – Analytics): an opt-out analytics will not send behavioral data

2. Reception of Test push OK but I do not receive campaigns (iOS)

Test pushs are both sent to APNS through Production and Sandbox whereas “real” campaigns sent from GROW solely use APNS Production.

Verify your app is built in release mode to ensure campaign reception.

3. Missing App Group (iOS)

If you get the message “An app group must be set…” in the console, this means the SDK has been initialised without an app group defined on the SDK Configuration. To solve this, make sure to pass a non-nil string for the SDK Configuration app group parameter

4. Invalid App Group (iOS)

If you get the message “Invalid app group.…” in the console, this means the app group identifier used at the SDK initialization is not recognized by the iOS framework. To solve this, make sure the provisioning profile used for your app target and notification service target contains the App Group entitlement and has the right app group identifier defined.

5. No push token

If there is no pushToken field in the api/deviceInfo request, as specified in the push integration verification section, this means there is a missing configuration on your project, or that there is a conflict with another library preventing the Grow SDK from retrieving the iOS token.

Please check that:

  • You have set and configured all the required capabilities on your application and extension targets
  • If you use another library that has push notification or analytics features (like Firebase), make sure the Grow SDK is the first library to be initialized in the AppDelegate’s application(_:didFinishLaunchingWithOptions:) method.

6. Request not Allowed

If you get, the “Request not allowed” error message in the console, this means the server has refused the SDK request at some point.

This can be for several reasons:

  • The app bundle id and the API key used in the SDK Configuration are not known by the platform. This message comes together with another message “either apiKey or applicationId doesn’t match an existing app on the Grow platform” which is printed only once by the SDK when it tries to retrieve the Server Configuration just after SDK is initialized. The SDK will retry to retrieve the Server Configuration from 4 hours after last retrieval attempt.
    To solve this, go to the Admins section on the platform, select your project and check that:
    • The bundle id is listed
    • The api key is the right one
    • Fix the problem and re-install the app to not have to wait for the 4 hours delay
  • The app requests limit has been reached. The SDK will retry to send requests from 24 hours after the first refused request.
  • The app has been revoked on the platform. The SDK will never retry to send any requests.

Advanced – Usage guide

Device

These methods allow you to identify users and manage notification and tracking consent

From the Device interface you have access to:

  • User identifier
  • Device identifier
  • Analytics enabled
  • Open Notification Settings If Needed Get Notifications Allowed
  • Request Notifications Authorization (iOS only)
  • Request Provisional Notifications Authorization (iOS only)

Identify Users

The following methods allow you to retrieve or value an identifier.

The Device ID is generated by GROW. It is not editable.

Retrieving User Identifier

Grow.Device.getUserId();

Updating User Identifier

Grow.Device.setUserId("userId");

Retrieving Device Identifier

 String deviceId = Grow.Device.getDeviceId();

Analytics

The following methods allow you to manage user analytics by GROW SDK.

For reporting activity logs from the tagging plan (User Identifier, Attributes & Events), analytics must be enabled in the SDK.

By default, analytics are disabled and can be turned on by changing the analytics state of the SDK

Retrieving Analytics Enabled Status

Boolean analyticsEnabled = Grow.Device.getAnalyticsEnabled();

Updating Analytics Status

Boolean enabled = true/false;  
Grow.Device.setAnalyticsEnabled(enabled);

Notifications Permissions

The following methods allow you to manage notifications settings according to iOS specificities.

Open Notification Settings If Needed

Grow.Device.openNotificationSettingsIfNeeded();

Get Notifications Allowed

//For Android
    Grow.Device.getNotificationsAllowed();

//For iOS
    Grow.Device.getNotificationsAllowed((returnValue)=>{
    //do something with `returnValue`
 });

Request Notifications Authorization

Request Notifications Authorization is available for iOS only!
Grow.Device.requestNotificationAuthorization();

Request Provisional Notifications Authorization

Request Provisional Notifications Authorization is available for iOS only!
Grow.Device.requestProvisionalNotificationAuthorization();

Events

These methods are dedicated to the implementation of the tagging plan. They allow you to define events to track the activity of your users

These methods only will work with users who are “opt-in analytics”

From the Events interface, you have access to:

  • Custom events
  • Location events

Send a Simple Custom event

String name = "event_name";
Grow.Events.Custom.Create(name).Send();

Send a Custom Event with a Parameter

String name = "event_name";
String value = "Parameter value";
String key = "a_key";

Grow.Events.Custom.Create(name)
                  .Put(key, value)
                  .Send();

Send a Location Event

If you wish, you can log the GPS coordinates of your users if they have their GPS enabled and the application is authorized to use these coordinates.
Grow.Events.Location.send(Location);

Attributes

These methods are dedicated to the implementation of the tagging plan. They allow you to define the status of a user based on its activity.

These methods will only work with users who are “opt-in analytics”.
Attributes require a defined user identifier.

From the Attributes interface, you have access to:

  • String attributes
  • Number attributes
  • Boolean attributes
  • Date attributes

String Attributes

Setting a String Attribute

Grow.Attributes.setString("key", "value");

Removing a String Attribute

var key = "a_key";
Grow.Attributes.SetString(key, null);

Number Attributes

Setting a Number Attribute

Grow.Attributes.setNumber("key", 1);

Removing a Number Attribute

var key = "a_key";
Grow.Attributes.SetNumber(key, null);

Boolean Attributes

Setting a Boolean Attribute

Grow.Attributes.setBoolean("key", true);

Removing a Boolean Attribute

var key = "a_key";
Grow.Attributes.SetBoolean(key, null);

Date Attributes

Setting a Date Attribute

Grow.Attributes.setDate("key", new Date());

Removing a Date Attribute

var key = "a_key";
Grow.Attributes.SetDate(key, null);

Campaigns

The following methods allow you to pause and resume the display of in-apps in specific paths of your application.

Pausing Campaign Display

Grow.Device.pauseInAppDisplaying();

Resuming Campaign Display

Grow.Device.resumeInAppDisplaying();

Privacy

These methods allow you to manage the collection and deletion of your users’ data.

From the Privacy interface, you have access to:

  • Request to Collect Data
  • Request to Erase Data
  • Request to Remove Account
  • Set Tracking Allowed

Request to Collect Data

Grow.Privacy.requestToCollectData();

Request to Erase Data

Grow.Privacy.requestToEraseData();

Request to Remove Account

Grow.Privacy.requestToRemoveAccount();

Set Tracking Allowed

The purpose of this method is to track the status of the device related to the Apple tracking transparency and the related consent the user provided.
boolean allowed = true/false;
Grow.Privacy.setTrackingAllowed(allowed);