Xamarin.Forms

Prev Next

A integração do Xamarin.Forms requer os passos desta página além daqueles abordados no guia principal de integração do Xamarin.

Integração

São necessários três arquivos para adicionar a funcionalidade Xtremepush ao seu aplicativo Xamarin.Forms. São eles a interface Xtremepush e sua implementação para as plataformas Android e iOS.

Adicione o IXPushDelegate à seção de código compartilhado do seu app.

300

Abra o IXPushDelegate espaço e certifique-se de mudar o namespace para o seu.

Adicione os XPushDelegate.cs arquivos das pastas Android e iOS à seção da plataforma relevante. Novamente, depois, você precisará abrir esses arquivos e mudar o namespace para o seu.

Para Android, você também precisará adicionar o pacote Plugin.CurrentActivity nuget e inicializá-lo na sua classe de aplicação.

Usando Xtremepush

Uma vez que o projeto tenha sido configurado com uma interface comum e implementações para cada plataforma, use o DependencyService para obter a implementação correta em tempo de execução.

Exemplo para chamar hitTag:

DependencyService.Get<IXPushDelegate>().HitTag("SampleTag");

As APIs disponíveis são:

//sends a single string tag to the platform
DependencyService.Get<IXPushDelegate>().HitTag("TagTitle");

        //sends a tag key-value pair tag consisting of title and value to the platform
DependencyService.Get<IXPushDelegate>().HitTag("TagTitle", "TagValue");

        //sends an event to the platform
DependencyService.Get<IXPushDelegate>().HitEvent("SampleEvent");

        //sends an event key-value pair tag consisting of title and value to the platform
DependencyService.Get<IXPushDelegate>().HitEvent("SampleEvent", "WithValue");

        //opens up the Xtremepush inbox
DependencyService.Get<IXPushDelegate>().OpenInbox();

        //Sets subscribed to push messages as true or false
DependencyService.Get<IXPushDelegate>().SetSubscription(true);

        //Sets the Id associated with the user
DependencyService.Get<IXPushDelegate>().SetUser("UserId");

        //Returns an iDictionary containing details about device
DependencyService.Get<IXPushDelegate>().GetDeviceInfo();

        //Sends request to XPush to get list of push messages, 
                //uint offset = amount from latest to return messages
                //uint limit = number of messages to be returned
DependencyService.Get<IXPushDelegate>().GetPushList(offset, limit);

        //Marks a message as opened (This is tracked automatically so this is not required in most situations) 
                //string messageId = the id of the message to mark as opened
//DependencyService.Get<IXPushDelegate>().MarkPushAsRead(messageId);

Usando o GetPushList

Android

No Android, para lidar com a lista de mensagens retornadas, você deve implementar a IPushListListener interface.

Essa interface possui um único método PushListReceived. Um exemplo é mostrado abaixo.

public class MainApplication : Application, Application.IActivityLifecycleCallbacks, IPushListListener
    {
        ...

        public void PushListReceived(IList<Message> p0, Java.Lang.Ref.WeakReference p1)
        {
            try
            {
                foreach (Message m in p0){
                    Log.Debug("XPushExample", "create_time: " + m.Metadata["create_time"]);
                }
            } catch (Exception e)
            {
                Log.Debug("XPushExample", "Empty message list received");
            }
        }
    }

iOS

No iOS, no XPushDelagate.cs file, GetPushList toma um método de callback como seu terceiro parâmetro. Isso é definido como padrão, para um método chamado PushListCallback, que também está no arquivo. No entanto, você pode mudar isso por outro método, se quiser.

Um exemplo de implementação no iOS:

public void GetPushList(uint offset, uint limit)
{
      //replace PushListCallback with your callback function if named differently
      XP.XPush.GetPushNotificationsOffset(offset, limit, PushListCallback);
}

public void PushListCallback(Foundation.NSArray arg1, Foundation.NSError arg2) {
      try
      {
          for (nuint i = 0; i < arg1.Count; i++){
              XP.XPMessage xpm = arg1.GetItem<XP.XPMessage>(i);
              System.Diagnostics.Debug.WriteLine("XPushExample - create_time: " + xpm.Metadata["create_time"]);
          }
      } catch (Exception e)
      {
          System.Diagnostics.Debug.WriteLine("XPushExample - Empty message list received");
      }
}

Objeto de Mensagem Xtremepush

O XPush objeto Message contém as seguintes chaves:

  • ID: O ID da mensagem

  • Título: O título da mensagem

  • Texto: O texto da mensagem

  • ID da campanha: O ID da campanha Xtremepush

  • Dados: Os dados incluem informações adicionais, como cargas úteis associadas à mensagem

  • Metadados: Dados adicionais sobre a mensagem, como create_time e read (usuário clicou na mensagem)

O processo de deep linking na aplicação Xamarin Forms é o mesmo do processo padrão para adicionar deeplinks, descrito em nosso guia dedicado, com algumas mudanças adicionais.

No projeto Forms, implemente o ouvinte no formato abaixo:

[Application]
public class MainApplication : Application, IInboxBadgeUpdateListener, IDeeplinkListener
{
    public MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }


    public void InboxBadgeUpdated(int i, Java.Lang.Ref.WeakReference activityHolder)
    {
        //print out inbox badge 
        Log.Debug("Inbox Badge is : ", i + "");
    }

    public override void OnCreate()
    {
        base.OnCreate();
        // If using Xamarin.Forms please install the Plugin.CurrentActivity package
        // from NuGet and uncomment the line below
        // CrossCurrentActivity.Current.Init(this);

        String XPUSH_APP_KEY = "";
        String GOOGLE_PROJECT_NUMBER = "";
        new PushConnector.Builder(XPUSH_APP_KEY, GOOGLE_PROJECT_NUMBER)
                            .TurnOnDebugLogs(true)
                            .SetDeeplinkListener(this)
                            .Create(this);

    }
}

Chame o IDeeplinkListener dentro da própria classe e defina o DeepLinkListener dentro do construtor PushConnector:

.setDeeplinkListener(this)

Para iOS, o método de deeplink precisa ser registrado da seguinte forma:

(void)registerDeeplinkHandler: (XPDeeplinkCallback)callback;

Uma vez que esses métodos são implementados no projeto Xamarin Forms, o restante da configuração do deeplink pode ser retirado do guia do usuário do deeplink.