Push Sharp не отправляет уведомление и не перезванивает в Push-сервисе

Я использую pushsharp для создания удаленных уведомлений на своем устройстве. Я сделал все, что нужно для сертификата. Моя проблема в том, что когда я пытаюсь отправить уведомление с помощью резкого нажатия, ничего не происходит, вот мой код, который я взял из Здесь. Я бы, по крайней мере, ожидал, что некоторые из обратных вызовов будут вызываться, например, NotificationFailed, ChanelCreated... и т.д.

Вот мой код

открытый класс PushNotificationService { частный статический PushNotificationApple _pushNotificationApple;

    public static void Main()
    {
        PushNotificationService ser = new PushNotificationService();
       string token = "0eaaf46d379bc5f5529f0b3357e0973ccd4655b163d789d875e3ad5fe64210d9";
        ser.SendPushNotification(token, "Hello my push");
        System.Console.WriteLine("Test");
    }


    public PushNotificationService()
    {
        if (_pushNotificationApple == null)
        {
            _pushNotificationApple = new PushNotificationApple();
        }
    }

    /// <summary>
    /// Send the push notification to the device
    /// </summary>
    /// <param name="deviceToken">The device token</param>
    /// <param name="message">The message</param>
    /// <returns>True if the notification is sent</returns>
    public bool SendPushNotification(string deviceToken, string message)
    {
        if (_pushNotificationApple != null)
        {
            _pushNotificationApple.SendNotification(deviceToken, message);
        }
        return true;
    }
}

Другой класс

/// <summary>
/// Class for
/// </summary>
public class PushNotificationApple
{
    private static PushBroker pushBroker;

    /// <summary>
    /// The push notification apple
    /// </summary>
    public PushNotificationApple()
    {
        if (pushBroker == null)
        {
            //Create our push services broker
            pushBroker = new PushBroker();

            //Wire up the events for all the services that the broker registers
            pushBroker.OnNotificationSent += NotificationSent;
            pushBroker.OnChannelException += ChannelException;
            pushBroker.OnServiceException += ServiceException;
            pushBroker.OnNotificationFailed += NotificationFailed;
            pushBroker.OnNotificationRequeue += NotificationRequeue;
            pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            pushBroker.OnChannelCreated += ChannelCreated;
            pushBroker.OnChannelDestroyed += ChannelDestroyed;

            //-------------------------
            // APPLE NOTIFICATIONS
            //-------------------------
            //Configure and start Apple APNS
            // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to generate one for connecting to Sandbox,
            //   and one for connecting to Production.  You must use the right one, to match the provisioning profile you build your
            //   app with!
            // Make sure you provide the correct path to the certificate, in my case this is how I did it in a WCF service under Azure,
            // but in your case this might be different. Putting the .p12 certificate in the main directory of your service 
            // (in case you have a webservice) is never a good idea, people can download it from there..
            //System.Web.Hosting.HostingEnvironment.MapPath("~/folder/file");


             var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/PushNotification.p12"));

            //var appleCert = File.ReadAllBytes("/Resources/PushNotification.p12");

            // TODD revise
            // var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/PushSharp.PushCert.Development.p12"));

            //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server 
            //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
            //  If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
            //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')
            pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "")); //Extension method
        }
    }

    private void NotificationRequeue(object sender, PushSharp.Core.NotificationRequeueEventArgs e)
    {
        Console.WriteLine("Chanel Notification Requeue");
    }

    public void SendNotification(string deviceToken, string message)
    {
        //Fluent construction of an iOS notification
        //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
        //  for registered for remote notifications is called, and the device token is passed back to you
        if (pushBroker != null)
        {
            pushBroker.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(deviceToken)
                                       .WithAlert(message)
                                       .WithBadge(10)
                                       .WithSound("sound.caf"));
        }
    }

    private void ChannelDestroyed(object sender)
    {
        Console.WriteLine("Chanel Destroyed");
    }

    private void ChannelCreated(object sender, PushSharp.Core.IPushChannel pushChannel)
    {
        Console.WriteLine("Chanel created");
    }

    private void DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, PushSharp.Core.INotification notification)
    {
        Console.WriteLine("Device Subscription Changed");
    }

    private void DeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, PushSharp.Core.INotification notification)
    {
        Console.WriteLine("Device Subscription Expired");
    }

    private void NotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
    {
        Console.WriteLine("Notification Failed");
    }

    private void ServiceException(object sender, Exception error)
    {
        Console.WriteLine("Service Exception");
    }
    private void ChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
    {
        Console.WriteLine("Channel Exception");
    }

    private void NotificationSent(object sender, PushSharp.Core.INotification notification)
    {
        Console.WriteLine("Notification Sent");
    }
}

person Amete Blessed    schedule 02.04.2015    source источник


Ответы (2)


Это решило мою проблему:

При создании производственного SSL-сертификата не меняйте имя «aps_production.cer».

И прежде чем создавать сертификаты, связанные с разработкой, сначала создайте сертификаты (SSL, provisioning, p12) только для производства и попробуйте.

Это действительно сработало для меня после того, как я попробовал разные подходы. Попробуйте.

person Durga Sriram    schedule 06.04.2015

Добавление этой строки в конце метода SendNotification() решило мою проблему.

pushBroker.StopAllServices();
person Amete Blessed    schedule 11.05.2015