2017-02-16 3 views
1

CrossPushNotificationListenerクラスにIPushNotificationListenerを実装しました。 READMEファイルに示唆されているとおりです。Xamarinフォームで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 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); 
    } 
} 

ユーザーが/登録アプリケーションにログインします、それを入力した後、私の共有コードでは、:PushNotificationApplicationDelegate.txt.ppファイルに示すように

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にも拡張していますホーム画面、私は電話する:

CrossPushNotification.Current.Register(); 

私はこのメソッドが実行されていると知っているので、私はアクセス許可を要求するアラートを得る。しかし、CrossPushNotificationListenerに実装されているIPushNotificationListenerインターフェイスのメソッドはどれも呼び出されません。

私はここで何が欠けていますか?

ありがとうございます。

+0

?最初にデバイスが正しく登録され、プッシュ通知がAppleプッシュ通知サービスに配信されていることを確認する必要があります。 – hankide

+0

CrossPushNotificationListenerのメソッドが呼び出されることはないため、デバイストークンが取得されません。AppDelegateのメソッドもありません。私は許可アラートの要求を取得すると、レジスタが発生します。このビットは私をさらに混乱させています... – nmdias

答えて

0

iOSの上では、呼び出しを試みなければならない:

CrossPushNotification.Initialize<CrossPushNotificationListener>(); 

LoadApplication(new Origination.App()); 

後にこのように:DependencyServiceと

 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

カスタム実装。このコードは、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 
関連する問題