EN  | 

ES
/Quick Integration Guide /App push notifications /Xamarin

Xamarin integration

Quick Guide to Integration of the Xamarin SDK.

Index

What do you need for integration?

It is important since the project contains the configuration data of your application, that is, the domain where your website is hosted, the safari or iOS certificates or the firebase key that android uses. It all depends on the platforms (web or app) that the project uses.

Integration

This article shows the minimum development that must be done to start registering devices and being able to carry out the first push campaigns.


Our SDK is available through NuGet.

NuGet it is a package management system. It consists of a command line client and an online database of public and private packages.

Import the plugin

To add our SDK to your project through NuGet you have to look for the Com.Indigitall.Xamarin package.

Add this package to your project (PCL, Android and iOS) as follows:



This integration has been done with the IDE Visual Studio.

Android Settings

You can see it in this tutorial video or read the instructions below:



Adding Firebase Services

  1. To start you need a file called google-services.json . This file can be exported from the Firebase console . Move it to the root folder of your project .


  1. Add the services from indigitall to your AndroidManifest.xml as you can see below.


<manifest ...>
  <!-- ... -->
  <!-- START indigitall permissions -->
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <!-- END indigitall permissions -->

  <application ...>
    <!-- ... -->

    <!-- START indigitall services -->
    <service android:name="com.indigitall.android.services.StatisticService" />
    <service android:name="com.indigitall.android.services.NightService" />
    <receiver android:name="com.indigitall.android.receivers.BootReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>
    <receiver android:name="com.indigitall.android.receivers.LocationReceiver">
      <intent-filter>
        <action android:name="LocationReceiver.Action.LOCATION_UPDATE" />
      </intent-filter>
    </receiver>
    <service android:name="com.indigitall.android.services.FirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>

    <meta-data android:name="indigitall.color" android:resource="@color/colorprimary" />
    <meta-data android:name="indigitall.icon" android:resource="@mipmap/launcher_foreground" />
    <!-- END indigitall services -->

  </application>
</manifest>

Adding HMS Services

  1. To start you need a file called agconnect-services.json . This file can be exported from the Huawei developer console .

  2. Copy agconnect-services.json into the Assets folder of your project.

  3. Create a file HmsLazyInputStream.cs in the root of the project that will be used to read the content of agconnect-services.json .


HMS HmsLazyInputStream


  1. Add the following code in the AttachBaseContext of the MainActivity to call HmsLazyInputStream.cs :


protected override void AttachBaseContext(Context context)
{
    base.AttachBaseContext(context);
    AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
    config.OverlayWith(new HmsLazyInputStream(context));
}


  1. Add the following code in HmsLazyInputStream.cs
using System;
using System.IO;
using Android.Content;
using Android.Util;
using Com.Huawei.Agconnect.Config;

namespace XamarinDemo.Droid
{
    public class HmsLazyInputStream : LazyInputStream
    {
        public HmsLazyInputStream(Context context) : base(context)
        {
        }

        public override Stream Get(Context context)
        {
            try
            {
                return context.Assets.Open("agconnect-services.json");
            }
            catch (Exception e)
            {
                Log.Error(e.ToString(), "Can't open agconnect file");
                return null;
            }
        }
    }
}


  1. Add the following HMS Nuget packages to have the push and location services in your application:


HMS Nugets


  1. Add the HMS services indigitall in your AndroidManifest.xml .
<!--HMS Services START-->
<service android:name="Com.Huawei.Hms.Location.LocationServices"></service>
<service android:name="com.indigitall.android.services.HMSMessagingService" android:exported="false">
    <intent-filter>
            <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
    </intent-filter>
</service>
<!--HMS Services END-->

Configuration for iOS

You can see it in this tutorial video or read the instructions below:




To start with the iOS configuration, make sure you have OK these points:



Nota: For the SDK to work correctly the FinishedLaunching method must be called from the AppDelegate class, before the call to the LoadApplication method occurs.


The AppDelegate class should look like this:


public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    Forms.Init();
    DependencyService.Register<Com.Indigitall.Xamarin.iOS.Indigitall>();

    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
    {
        // iOS 10 or later
        var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
        UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
        {
            if (granted)
            {
                InvokeOnMainThread(() =>
                {
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                });
            }
        });

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.Current.Delegate = new Com.Indigitall.Xamarin.iOS.UserNotificationCenterDelegate();

    }
    else
    {
        // iOS 9 or before
        var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
        var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
        UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
    }
    ...
    UNUserNotificationCenter.Current.Delegate = new Com.Indigitall.Xamarin.iOS.UserNotificationCenterDelegate();
    ...
    LoadApplication(new App());

    return base.FinishedLaunching(app, options);
}

[Export("application:didRegisterForRemoteNotificationsWithDeviceToken:")]
override public void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    IndigitallXamarin.Indigitall.SetDeviceToken(deviceToken, (device) =>
    {
        Console.WriteLine("NewUserRegistered: " + device.DeviceID);
    });
}

[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public virtual void DidReceiveNotificationResponse(UserNotifications.UNUserNotificationCenter center, UserNotifications.UNNotificationResponse response, Action completionHandler)
    {
        IndigitallXamarin.Indigitall.HandleWithResponse(response);
    }

//@DEPRECATED
[Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")]
override public void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
    IndigitallXamarin.Indigitall.HandleWithNotification(userInfo, null);
}

//@DEPRECATED
[Export("application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler:")]
override public void HandleAction(UIApplication application, string actionIdentifier, NSDictionary remoteNotificationInfo, NSDictionary responseInfo, Action completionHandler)
{
    IndigitallXamarin.Indigitall.HandleWithNotification(remoteNotificationInfo, actionIdentifier);
}

Notification Service Extension

Since the release of iOS 10 , apps can manage rich push notifications , that is, with images, gif, video, buttons, etc.

In order to use these features, your app needs to implement the Notification Service Extension.


  1. Add a new Notification Service Extension project to your solution
  2. Add the dependency Com.Indigitall.Xamarin from NuGet
  3. Reference the target extension in your iOS project
  4. Once you've created the extension, a new file is created within the project. It's the NotificationService. Replace its content with the following lines:


using System;
using Foundation;
using Com.Indigitall.Xamarin.iOS;

namespace Notification
{
    [Register("NotificationService")]
    public class NotificationService : UNNotificationServiceExtension
    {
        Action<UNNotificationContent> ContentHandler { get; set; }
        UNMutableNotificationContent BestAttemptContent { get; set; }
        UNNotificationRequest _request { 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();
            _request = request;

            // Modify the notification content here...
            IndigitallXamarin.Indigitall.DidReceiveNotificationRequest(_request, ContentHandler);
        }

        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.
            if (ContentHandler != null && BestAttemptContent != null)
            {
                IndigitallXamarin.Indigitall.ServiceExtensionTimeWillExpire(BestAttemptContent, ContentHandler);
            }

        }
    }
}

SDK initialization

You can see it in this tutorial video or read the instructions below:




Initialize the SDK with the call to the Indigital.init method.

First you have to call the IIndigitall interface inside your MainPage class, as we see below:


IIndigitall indigitall = DependencyService.Get<IIndigitall>();
if (indigitall != null)
{
    indigitall.Init("<YOUR_APP_KEY>", "<YOUR_SENDER_ID>");
}



Consola de Firebase Consola de Firebase



Add the following code snippet in the OnCreate method from your main application screen. The code snippet must be added before calling _Xamarin's own LoadApplication method.


protected override void OnCreate(Bundle bundle)
{
    DependencyService.Register<Com.Indigitall.Xamarin.Android.Indigitall>();
    Com.Indigitall.Android.Indigitall.SetDefaultActivity(this, "YOUR ACTIVITY");
    var app = new App();
    Com.Indigitall.Xamarin.Android.Utils.PermissionUtils.RequestLocationPermission(this);
    LoadApplication(app);
}

Validate the integration

To verify that the integration was successful, do the following:


  1. From Visual Studio, go to the log tab and look for the PUT / device call containing the parameters appKey, deviceId and pushToken and which returns HTTP 200.




  1. Send a notification from the indigitall console. It is possible that the device counter appears to 0 on the console. Don't worry, it may take a few minutes to update, but you don't have to wait, the push should still arrive.



Resources