2017-02-16 57 views
1

我已经在我的CrossPushNotificationListener类中实施了IPushNotificationListener。正如README文件中所建议的那样。如何在Xamarin Forms中实现CrossPushNotification插件?

public class CrossPushNotificationListener : IPushNotificationListener 
{ 
    void IPushNotificationListener.OnError(string message, DeviceType deviceType) 
    { 
     Application.Current.MainPage.DisplayAlert("error", message, "ok"); 
    } 

    void IPushNotificationListener.OnMessage(JObject values, DeviceType deviceType) 
    { 
     Application.Current.MainPage.DisplayAlert("message", values.ToString(), "ok"); 
    } 

    void IPushNotificationListener.OnRegistered(string token, DeviceType deviceType) 
    { 
     Application.Current.MainPage.DisplayAlert("token", token, "ok"); 
    } 

    void IPushNotificationListener.OnUnregistered(DeviceType deviceType) 
    { 
     Application.Current.MainPage.DisplayAlert("unregistered", "", "ok"); 
    } 

    bool IPushNotificationListener.ShouldShowNotification() 
    { 
     Application.Current.MainPage.DisplayAlert("should show notification", "", "ok"); 
     return true; 
    } 
} 

在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); 
} 

我也用适当的覆盖延伸的AppDelegate如图所示PushNotificationApplicationDelegate.txt.pp文件:

public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) 
{ 
    if (CrossPushNotification.Current is IPushNotificationHandler) 
    { 
     ((IPushNotificationHandler)CrossPushNotification.Current).OnErrorReceived(error); 
    } 
} 

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) 
{ 
    if (CrossPushNotification.Current is IPushNotificationHandler) 
    { 
     ((IPushNotificationHandler)CrossPushNotification.Current).OnRegisteredSuccess(deviceToken); 
    } 
} 


public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) 
{ 
    if (CrossPushNotification.Current is IPushNotificationHandler) 
    { 
     ((IPushNotificationHandler)CrossPushNotification.Current).OnMessageReceived(userInfo); 
    } 
} 


public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo) 
{ 
    if (CrossPushNotification.Current is IPushNotificationHandler) 
    { 
     ((IPushNotificationHandler)CrossPushNotification.Current).OnMessageReceived(userInfo); 
    } 
} 

后来,在我的共享代码,用户注册后/登录的应用程序,然后输入它的主屏幕,我打电话:

CrossPushNotification.Current.Register(); 

我知道这个方法正在执行,因为我得到了一个警告请求权限。但是,调用CrossPushNotificationListener中实现的IPushNotificationListener接口中的方法都不是。

我在这里错过了什么?

谢谢。

+0

您使用的推送通知传递什么样的服务?您应该首先检查设备是否已正确注册,并将推送通知传送到Apple推送通知服务。 – hankide

+0

CrossPushNotificationListener中的方法永远不会被调用,所以我没有获取设备令牌。AppDelegate中的方法也不是。注册发生,因为我收到请求权限警报。这一点让我更加困惑...... – nmdias

回答

0

在iOS你必须尝试拨打:

CrossPushNotification.Initialize<CrossPushNotificationListener>(); 

LoadApplication(new Origination.App()); 

像这样:

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

     LoadApplication(new App()); 

     CrossPushNotification.Initialize<CrossPushNotificationListener>(); 
     return base.FinishedLaunching(app, options); 
    } 
+0

不是这样。我最终创建了一个类似于插件的实现的依赖服务,并且工作。谢谢。 – nmdias

+1

是否有可能分享你的实现,并选择它作为你的问题的答案,有兴趣看看你是如何使用依赖服务去解决它的? –

1

与DependencyService自定义实现。此代码基于Xam.Plugin.PushNotification插件提供的解决方案。

共享项目

接口

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(); 
    } 

} 

这个电话在适当的时机,以索要权限

用户
DependencyService.Get<INotificationService>().Register(); 

IOS项目

[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