| ES
guía rápida de integración del SDK de Xamarin.
Es importante ya que el proyecto contiene los datos de configuración de tu aplicación, es decir, el dominio donde esta alojada tu web, los certificados de safari o iOS o la clave de firebase que usa android. Todo depende de las plataformas (web o app) que use el proyecto.
Este artículo muestra el desarrollo mínimo que hay que hacer para comenzar a registrar dispositivos y poder realizar las primeras campañas push.
Nuestro SDK está disponible a través de NuGet.
NuGet es un sistema de gestión de paquetes. Consiste en un cliente de línea de comandos y una base de datos en línea de paquetes públicos y privados.
Para añadir nuestro SDK a tu proyecto a través de NuGet tienes que buscar el paquete Com.Indigitall.Xamarin.
Añade este paquete a tu proyecto (PCL, Android e iOS) de la siguiente manera:
Esta integración se ha realizado con el IDE Visual Studio.
Puedes verlo en ente vídeo tutorial o leer las instrucciones más abajo:
<!-- 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>
Para comenzar necesitas un fichero llamado agconnect-services.json. Este fichero lo podrás exportar desde la consola para desarrolladores de Huawei.
Copia agconnect-services.json en la carpeta Assets de tu proyecto.
protected override void AttachBaseContext(Context context)
{
base.AttachBaseContext(context);
AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
config.OverlayWith(new HmsLazyInputStream(context));
}
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;
}
}
}
}
<!--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-->
Puedes verlo en ente vídeo tutorial o leer las instrucciones más abajo:
Para comenzar con la configuración de iOS, asegúrate tener OK estos puntos:
Nota: para que el SDK funcione correctamente el método FinishedLaunching debe ser llamado desde la clase AppDelegate, antes de que se produzca la llamada al método LoadApplication
La clase AppDelegate debería quedar así:
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);
}
Desde la salida de iOS 10, las apps pueden gestionar notificaciones push enriquecidas, es decir, con imágen, gif, vídeo, botones, etc.
Para poder hacer uso de estas funcionalidades, tu app necesita implementar el Notification Service Extension.
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);
}
}
}
}
Puedes verlo en ente vídeo tutorial o leer las instrucciones más abajo:
Inicializa el SDK con la llamada al metodo Indigital.init.
Primero hay que llamar a la interfaz IIndigitall dentro de tu clase MainPage, como vemos a continuación:
IIndigitall indigitall = DependencyService.Get<IIndigitall>();
if (indigitall != null)
{
indigitall.Init("<YOUR_APP_KEY>", "<YOUR_SENDER_ID>");
}
Añade el siguiente fragmento de código en el método OnCreate desde la que sea tu pantalla principal de la aplicación. El fragmento de código debe añadirse antes de llamar al método LoadApplication propio de Xamarin.
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);
}
Para comprobar que la integración se ha realizado correctamente realiza lo siguiente: