Dmitry
Dmitry

Reputation: 315

Call method in xamarin.ios from PCL project

In my Xamarin.iOS project in AppDelegate class I have method:

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);

    Hub.UnregisterAllAsync (deviceToken, (error) => {
        if (error != null)
        {
            System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
            return;
        }

        NSSet tags = null; // create tags if you want
        Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
            if (errorCallback != null)
                System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
        });
    });
}

How I can call it from my PCL project?

Upvotes: 2

Views: 582

Answers (1)

SergioAMG
SergioAMG

Reputation: 428

a) Create an interface in your PCL project:

namespace YourNamespace.Interfaces
{
    public interface IRemoteNotifications
    {
        void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken);
    }
}

b) Create a class that will implement this interface in your iOS project, remeber to decorate the class with the required attributes:

[assembly: Dependency(typeof(RemoteNotifications))]
namespace YourNamespace.iOS.DependencyService
{
    public class RemoteNotifications : IRemoteNotifications
    {
        public void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            // Place your custom logic here
        }
    }
}

c) Call your custom implementation from the PCL project using Dependency Service to locate the Interface implementation.

DependencyService.Get<IRemoteNotifications>().RegisteredForRemoteNotifications(application, deviceToken);

d) Execute your logic.

That is all you need.

Upvotes: 3

Related Questions