Push-уведомления Apple с использованием Moon-APNS или APNS-Sharp

Мне очень трудно понять, как отправлять сообщения с моего сервера на APNS. Я использовал Moon-APNS и APNS-Sharp, и я застрял с той же ошибкой, которая называется «неверный параметр». Я сгенерировал файл p12, используя KeyChain. Я перетащил файл в виртуальную среду Win 7 и поместил его в папку bin\debug. Вот код для Moon-APNS:

 static void Main(string[] args)
        {
            var deviceToken = "21212d6fefebde4d317cab41afff65631b5a4d47e5d85da305ec610b4013e616";

            var payload = new NotificationPayload(deviceToken, "hello world");
            var notificationList = new List<NotificationPayload>() { payload };

            var push = new PushNotification(true, "PushNotificationTest.p12", "pushchat");
            var result = push.SendToApple(notificationList);

            Console.WriteLine("Hello World");  
        }

У кого-нибудь есть идеи?


person azamsharp    schedule 16.08.2011    source источник


Ответы (3)


Я думаю, это поможет вам:

Брелок OSX

После того, как вы создали соответствующий сертификат push-уведомлений на портале программы для разработчиков iPhone, вы должны были загрузить файл с именем, например, apn_developer_identity.cer. Если вы еще этого не сделали, вам следует открыть/импортировать этот файл в Связку ключей, в раздел входа в систему.

Наконец, если вы отфильтруете связку ключей, чтобы отобразить сертификаты контейнера входа в систему, вы должны увидеть свой сертификат в списке. Разверните сертификат, и под ним/прикрепленным к нему должен быть ключ.

Щелкните правой кнопкой мыши или Ctrl+щелчок по соответствующему сертификату и выберите Экспорт. Связка ключей попросит вас выбрать пароль для экспорта. Выберите один и запомните его. У вас должен получиться файл .p12. Вам понадобится этот файл и пароль, который вы выбрали, чтобы использовать библиотеки уведомлений и отзывов здесь. OpenSSL

Вот как создать файл формата PKCS12 с использованием открытого ssl, вам понадобится ваш закрытый ключ разработчика (который можно экспортировать из цепочки для ключей) и CertificateSigningRequest??.certSigningRequest

1. Convert apn_developer_identity.cer (der format) to pem:

openssl x509 -in apn_developer_identity.cer -inform DER -out apn_developer_identity.pem -outform PEM}

2. Next, Convert p12 private key to pem (requires the input of a minimum 4 char password):

openssl pkcs12 -nocerts -out private_dev_key.pem -in private_dev_key.p12

3. (Optional): If you want to remove password from the private key:

openssl rsa -out private_key_noenc.pem -in private_key.pem

4. Take the certificate and the key (with or without password) and create a PKCS#12 format file:

openssl pkcs12 -export -in apn_developer_identity.pem -inkey private_key_noenc.pem -certfile CertificateSigningRequest??.certSigningRequest -name "apn_developer_identity" -out apn_developer_identity.p12

Я обнаружил, что Moon-APNS проще в использовании и настройке в моем приложении.

person Alex    schedule 26.10.2011
comment
Может быть потому, что он твой? - person Martin Ingvar Kofoed Jensen; 11.05.2012

Решил проблему по ссылке:

http://code.google.com/p/apns-sharp/wiki/HowToCreatePKCS12Certificate

а затем создать файл .p12 с использованием подхода openssl.

person azamsharp    schedule 16.08.2011

Вы пытались использовать пример проекта APNS-Sharp для отправки уведомлений? Я использую аналогичный код, он отлично работает... вот как выглядит один из моих методов

 public void SendToSome(List<string> tokens)
    {
        //Variables you may need to edit:
        //---------------------------------
        bool sandbox = true;
        //Put your device token in here


        //Put your PKCS12 .p12 or .pfx filename here.
        // Assumes it is in the same directory as your app
        string p12File = "Certificates.p12";

        //This is the password that you protected your p12File 
        //  If you did not use a password, set it as null or an empty string
        string p12FilePassword = "";



        //Number of milliseconds to wait in between sending notifications in the loop
        // This is just to demonstrate that the APNS connection stays alive between messages
      //  int sleepBetweenNotifications = 15000;


        //Actual Code starts below:
        //--------------------------------

        string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

        NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

        service.SendRetries = 5; //5 retries before generating notificationfailed event
        service.ReconnectDelay = 5000; //5 seconds

        service.Error += new NotificationService.OnError(service_Error);
        service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

        service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
        service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
        service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
        service.Connecting += new NotificationService.OnConnecting(service_Connecting);
        service.Connected += new NotificationService.OnConnected(service_Connected);
        service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);

        //The notifications will be sent like this:
        //      Testing: 1...
        //      Testing: 2...
        //      Testing: 3...
        // etc...
        for (int i = 0; i < tokens.Count; i++)
        {
            //Create a new notification to send
            Notification alertNotification = new Notification();

            alertNotification.DeviceToken = tokens[i];
            alertNotification.Payload.Alert.Body = Text;
            alertNotification.Payload.Sound = "default";
            alertNotification.Payload.Badge = 1;

            //Queue the notification to be sent
            if (service.QueueNotification(alertNotification))
                Console.WriteLine("Notification Queued!");
            else
                Console.WriteLine("Notification Failed to be Queued!");

            //Sleep in between each message
            if (i < tokens.Count)
            {
               // Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
               // System.Threading.Thread.Sleep(sleepBetweenNotifications);
            }
        }

        Console.WriteLine("Cleaning Up...");

        //First, close the service.  
        //This ensures any queued notifications get sent befor the connections are closed
        service.Close();

        //Clean up
        service.Dispose();


    }
person Daniel    schedule 16.08.2011
comment
Я решил свою проблему, создав файл .p12, используя подход openssl вместо использования KeyChain. Вот ссылка, по которой я перешел: code.google.com/p/apns-sharp /wiki/HowToCreatePKCS12Certificate - person azamsharp; 16.08.2011