C# 如何在Xamarin表单中实现CrossPushNotification插件?

C# 如何在Xamarin表单中实现CrossPushNotification插件?,c#,xamarin,push-notification,xamarin.ios,xamarin.forms,C#,Xamarin,Push Notification,Xamarin.ios,Xamarin.forms,我已经在我的CrossPushNotificationListener类中实现了IPushNotificationListener。正如文件中建议的那样 在iOS的AppDelegate中,我然后初始化CrossPushNotification插件 public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init ();

我已经在我的
CrossPushNotificationListener
类中实现了
IPushNotificationListener
。正如文件中建议的那样

在iOS的AppDelegate中,我然后初始化CrossPushNotification插件

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init ();

    CrossPushNotification.Initialize<CrossPushNotificationListener>();

    LoadApplication(new Origination.App ());
    return base.FinishedLaunching(app, options);
}
之后,在我的共享代码中,在用户注册/登录应用程序并进入其主屏幕后,我调用:

CrossPushNotification.Current.Register();
我知道正在执行此方法,因为我收到请求权限的警报。但是,在
CrossPushNotificationListener
中实现的
ipusNotificationListener
接口中没有任何方法被调用

我错过了什么


谢谢。

在iOS上,您必须尝试呼叫:

CrossPushNotification.Initialize<CrossPushNotificationListener>();
像这样:

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();

        LoadApplication(new App());

        CrossPushNotification.Initialize<CrossPushNotificationListener>();
        return base.FinishedLaunching(app, options);
    }
public override bool FinishedLaunching(UIApplication应用程序、NSDictionary选项)
{
全局::Xamarin.Forms.Forms.Init();
加载应用程序(新应用程序());
CrossPushNotification.Initialize();
返回基地。完成发射(应用程序,选项);
}

使用DependencyService的自定义实现。此代码基于插件提供的解决方案

共享项目

[assembly: Xamarin.Forms.Dependency(typeof (NotificationService))]
namespace App.iOS.Notifications
{
    public class NotificationService : INotificationService
    {

        public string Token
        {
            get
            {
                return NSUserDefaults.StandardUserDefaults.StringForKey(NotificationKeys.TokenKey);
            }

        }

        public void Register()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                UIUserNotificationType notificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(notificationTypes, new NSSet());
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
            }
        }

    }

}
接口

public interface INotificationListener
{
    void OnRegister(string deviceToken);
    void OnMessage(JObject values);
}

public interface INotificationService
{
    string Token { get; }
    void Register();
}
实施

public class NotificationListener : INotificationListener
{
    public void OnMessage(JObject values)
    {
        // TOOD: - Handle incoming notifications
    }

    public async void OnRegister(string deviceToken)
    {
        // TODO: - Register the devices token in the server
    }
}

public class NotificationManager
{

    private static NotificationManager _current = null;

    /// <summary>
    /// Shared instance of the Notification Manager
    /// </summary>
    public static NotificationManager Current
    {
        get
        {
            if (_current == null)
            {
                _current = new NotificationManager();
            }
            return _current;
        }
    }

    /// <summary>
    /// The member responsible for handling notifications
    /// </summary>
    public static INotificationListener Listener { get; private set; }

    /// <summary>
    /// Initializes the Notification Manager with an instance of the specified handler in type T
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static void Initialize<T>() where T: INotificationListener, new()
    {
        Listener = new T();
    }

}
应用程序代理

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    LoadApplication(new Origination.App ());
    NotificationManager.Initialize<NotificationListener>();
    return base.FinishedLaunching(app, options);
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    // Get current device token
    var DeviceToken = deviceToken.Description;
    if (!string.IsNullOrWhiteSpace(DeviceToken))
    {
        DeviceToken = DeviceToken.Trim('<').Trim('>').Replace(" ", "");
    }

    // Get previous device token
    var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey(NotificationKeys.TokenKey);

    // Has the token changed?
    if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
    {
        NotificationManager.Listener.OnRegister(DeviceToken);
    }

    // Save new device token 
    NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, NotificationKeys.TokenKey);
    NSUserDefaults.StandardUserDefaults.Synchronize();

}

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
    HandleNotification(userInfo);
}

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    HandleNotification(userInfo);
}

#region Handle Notification

private static string DictionaryToJson(NSDictionary dictionary)
{
    NSError error;
    var json = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);
    return json.ToString(NSStringEncoding.UTF8);
}

public void HandleNotification(NSDictionary userInfo)
{
    var parameters = new Dictionary<string, object>();
    var json = DictionaryToJson(userInfo);
    JObject values = JObject.Parse(json);

    var keyAps = new NSString("aps");

    if (userInfo.ContainsKey(keyAps))
    {
        NSDictionary aps = userInfo.ValueForKey(keyAps) as NSDictionary;

        if (aps != null)
        {
            foreach (var apsKey in aps)
            {
                parameters.Add(apsKey.Key.ToString(), apsKey.Value);
                JToken temp;
                if (!values.TryGetValue(apsKey.Key.ToString(), out temp))
                    values.Add(apsKey.Key.ToString(), apsKey.Value.ToString());
            }
        }
    }

    NotificationManager.Listener.OnMessage(values);
}

#endregion
public override bool FinishedLaunching(UIApplication应用程序、NSDictionary选项)
{
LoadApplication(新的Origination.App());
NotificationManager.Initialize();
返回基地。完成发射(应用程序,选项);
}
公共覆盖无效注册更正(UIApplication应用程序,NSData deviceToken)
{
//获取当前设备令牌
变量DeviceToken=DeviceToken.Description;
如果(!string.IsNullOrWhiteSpace(DeviceToken))
{
DeviceToken=DeviceToken.Trim(“”)。替换(“”,“”);
}
//获取上一个设备令牌
var oldDeviceToken=NSUserDefaults.StandardUserDefaults.StringForKey(NotificationKeys.TokenKey);
//代币换了吗?
if(string.IsNullOrEmpty(oldDeviceToken)| |!oldDeviceToken.Equals(DeviceToken))
{
NotificationManager.Listener.OnRegister(DeviceToken);
}
//保存新设备令牌
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken、NotificationKeys.TokenKey);
NSUserDefaults.StandardUserDefaults.Synchronize();
}
public override void DidReceiveEmotentification(UIApplication应用程序、NSDictionary userInfo、Action completionHandler)
{
HandleNotification(用户信息);
}
public override void ReceivedRemoteNotification(UIApplication应用程序,NSDictionary用户信息)
{
HandleNotification(用户信息);
}
#区域句柄通知
私有静态字符串字典(NSDictionary dictionary)
{
n误差;
var json=NSJsonSerialization.Serialize(字典,NSJsonWritingOptions.PrettyPrinted,out错误);
返回json.ToString(NSStringEncoding.UTF8);
}
公共无效句柄通知(NSDictionary userInfo)
{
var参数=新字典();
var json=DictionaryToJson(userInfo);
JObject value=JObject.Parse(json);
var keyAps=新NSString(“aps”);
if(userInfo.ContainsKey(keyAps))
{
NSDictionary aps=userInfo.ValueForKey(keyAps)作为NSDictionary;
如果(aps!=null)
{
foreach(aps中的var apsKey)
{
parameters.Add(apsKey.Key.ToString(),apsKey.Value);
JToken温度;
如果(!values.TryGetValue(apsKey.Key.ToString(),out temp))
Add(apsKey.Key.ToString(),apsKey.Value.ToString());
}
}
}
NotificationManager.Listener.OnMessage(值);
}
#端区

推送通知传递使用的是什么服务?您应该首先检查设备是否已正确注册,推送通知是否已发送到Apple推送通知服务。从未调用CrossPushNotificationListener中的方法,因此我无法获取设备令牌。AppDelegate中的方法也不是。当我收到权限请求警报时,发生了注册。这一点让我更加困惑…不是这样。我最终创建了一个依赖性服务,它的实现与插件类似,并且成功了。谢谢。是否可以分享您的实现,并选择它作为您问题的答案,有兴趣了解您如何使用依赖项服务?
public class NotificationListener : INotificationListener
{
    public void OnMessage(JObject values)
    {
        // TOOD: - Handle incoming notifications
    }

    public async void OnRegister(string deviceToken)
    {
        // TODO: - Register the devices token in the server
    }
}

public class NotificationManager
{

    private static NotificationManager _current = null;

    /// <summary>
    /// Shared instance of the Notification Manager
    /// </summary>
    public static NotificationManager Current
    {
        get
        {
            if (_current == null)
            {
                _current = new NotificationManager();
            }
            return _current;
        }
    }

    /// <summary>
    /// The member responsible for handling notifications
    /// </summary>
    public static INotificationListener Listener { get; private set; }

    /// <summary>
    /// Initializes the Notification Manager with an instance of the specified handler in type T
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static void Initialize<T>() where T: INotificationListener, new()
    {
        Listener = new T();
    }

}
DependencyService.Get<INotificationService>().Register();
[assembly: Xamarin.Forms.Dependency(typeof (NotificationService))]
namespace App.iOS.Notifications
{
    public class NotificationService : INotificationService
    {

        public string Token
        {
            get
            {
                return NSUserDefaults.StandardUserDefaults.StringForKey(NotificationKeys.TokenKey);
            }

        }

        public void Register()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                UIUserNotificationType notificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(notificationTypes, new NSSet());
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
            }
        }

    }

}
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    LoadApplication(new Origination.App ());
    NotificationManager.Initialize<NotificationListener>();
    return base.FinishedLaunching(app, options);
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    // Get current device token
    var DeviceToken = deviceToken.Description;
    if (!string.IsNullOrWhiteSpace(DeviceToken))
    {
        DeviceToken = DeviceToken.Trim('<').Trim('>').Replace(" ", "");
    }

    // Get previous device token
    var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey(NotificationKeys.TokenKey);

    // Has the token changed?
    if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
    {
        NotificationManager.Listener.OnRegister(DeviceToken);
    }

    // Save new device token 
    NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, NotificationKeys.TokenKey);
    NSUserDefaults.StandardUserDefaults.Synchronize();

}

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
    HandleNotification(userInfo);
}

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    HandleNotification(userInfo);
}

#region Handle Notification

private static string DictionaryToJson(NSDictionary dictionary)
{
    NSError error;
    var json = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);
    return json.ToString(NSStringEncoding.UTF8);
}

public void HandleNotification(NSDictionary userInfo)
{
    var parameters = new Dictionary<string, object>();
    var json = DictionaryToJson(userInfo);
    JObject values = JObject.Parse(json);

    var keyAps = new NSString("aps");

    if (userInfo.ContainsKey(keyAps))
    {
        NSDictionary aps = userInfo.ValueForKey(keyAps) as NSDictionary;

        if (aps != null)
        {
            foreach (var apsKey in aps)
            {
                parameters.Add(apsKey.Key.ToString(), apsKey.Value);
                JToken temp;
                if (!values.TryGetValue(apsKey.Key.ToString(), out temp))
                    values.Add(apsKey.Key.ToString(), apsKey.Value.ToString());
            }
        }
    }

    NotificationManager.Listener.OnMessage(values);
}

#endregion