2015-08-24 2 views
1

Я пытаюсь добавить уведомление толчка на Cordova/PhoneGap приложениях с использованием pushplugin https://github.com/phonegap-build/PushPluginCordova pushplugin не может получить маркер устройства в прошивкой

Я установил плагин с

cordova plugin add https://github.com/phonegap-build/PushPlugin.git 

Это кажется, что он работает потому что, когда я впервые запускаю приложение на своем устройстве (iPhone 5), он говорит: «ваше приложение хочет отправлять вам уведомления bla bla ...», но тогда я не получаю токен устройства: он должен показать предупреждение уже ,

Это, как я редактировал index.js по умолчанию, созданные Кордову:

var pushNotification; 
 
var app = { 
 
    // Application Constructor 
 
    initialize: function() { 
 
     this.bindEvents(); 
 
    }, 
 
    // Bind Event Listeners 
 
    // 
 
    // Bind any events that are required on startup. Common events are: 
 
    // 'load', 'deviceready', 'offline', and 'online'. 
 
    bindEvents: function() { 
 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
 
    }, 
 
    // deviceready Event Handler 
 
    // 
 
    // The scope of 'this' is the event. In order to call the 'receivedEvent' 
 
    // function, we must explicitly call 'app.receivedEvent(...);' 
 
    onDeviceReady: function() { 
 
     // app.receivedEvent('deviceready'); 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t // var pushNotification; 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t $("#app-status-ul").append('<li>deviceready event received</li>'); 
 
       
 
\t \t \t \t document.addEventListener("backbutton", function(e) 
 
\t \t \t \t { 
 
       \t $("#app-status-ul").append('<li>backbutton event received</li>'); 
 
    \t \t \t \t \t 
 
     \t \t \t \t if($("#home").length > 0) 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t // call this to get a new token each time. don't call it to reuse existing token. 
 
\t \t \t \t \t \t //pushNotification.unregister(successHandler, errorHandler); 
 
\t \t \t \t \t \t e.preventDefault(); 
 
\t \t \t \t \t \t navigator.app.exitApp(); 
 
\t \t \t \t \t } 
 
\t \t \t \t \t else 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t navigator.app.backHistory(); 
 
\t \t \t \t \t } 
 
\t \t \t \t }, false); 
 
\t \t \t 
 
\t \t \t \t try 
 
\t \t \t \t { 
 
       \t pushNotification = window.plugins.pushNotification; 
 
\t \t  $("#app-status-ul").append('<li>registering ' + device.platform + '</li>'); 
 
       \t if (device.platform == 'android' || device.platform == 'Android' || 
 
          device.platform == 'amazon-fireos') { 
 
\t \t \t pushNotification.register(successHandler, errorHandler, {"senderID":"661780372179","ecb":"onNotification"}); \t \t // required! 
 
\t \t \t \t \t } else { 
 
        \t pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); \t // required! 
 
       \t } 
 
       } 
 
\t \t \t \t catch(err) 
 
\t \t \t \t { 
 
\t \t \t \t \t txt="There was an error on this page.\n\n"; 
 
\t \t \t \t \t txt+="Error description: " + err.message + "\n\n"; 
 
\t \t \t \t \t alert(txt); 
 
\t \t \t \t } 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 

 

 

 

 

 

 

 
// handle APNS notifications for iOS 
 
      function onNotificationAPN(e) { 
 
       if (e.alert) { 
 
        $("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>'); 
 
        // showing an alert also requires the org.apache.cordova.dialogs plugin 
 
        navigator.notification.alert(e.alert); 
 
       } 
 
        
 
       if (e.sound) { 
 
        // playing a sound also requires the org.apache.cordova.media plugin 
 
        var snd = new Media(e.sound); 
 
        snd.play(); 
 
       } 
 
       
 
       if (e.badge) { 
 
        pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge); 
 
       } 
 
      } 
 
      
 
      // handle GCM notifications for Android 
 
      function onNotification(e) { 
 
       $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>'); 
 
       
 
       switch(e.event) 
 
       { 
 
        case 'registered': 
 
\t \t \t \t \t if (e.regid.length > 0) 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>"); 
 
\t \t \t \t \t \t // Your GCM push server needs to know the regID before it can push to this device 
 
\t \t \t \t \t \t // here is where you might want to send it the regID for later use. 
 
\t \t \t \t \t \t console.log("regID = " + e.regid); 
 
\t \t \t \t \t } 
 
        break; 
 
        
 
        case 'message': 
 
        \t // if this flag is set, this notification happened while we were in the foreground. 
 
        \t // you might want to play a sound to get the user's attention, throw up a dialog, etc. 
 
        \t if (e.foreground) 
 
        \t { 
 
\t \t \t \t \t \t \t $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>'); 
 
\t \t \t \t \t \t  
 
\t \t \t \t \t \t   // on Android soundname is outside the payload. 
 
\t \t \t \t \t     // On Amazon FireOS all custom attributes are contained within payload 
 
\t \t \t \t \t     var soundfile = e.soundname || e.payload.sound; 
 
\t \t \t \t \t     // if the notification contains a soundname, play it. 
 
\t \t \t \t \t     // playing a sound also requires the org.apache.cordova.media plugin 
 
\t \t \t \t \t     var my_media = new Media("/android_asset/www/"+ soundfile); 
 

 
\t \t \t \t \t \t \t my_media.play(); 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t \t else 
 
\t \t \t \t \t \t { \t // otherwise we were launched because the user touched a notification in the notification tray. 
 
\t \t \t \t \t \t \t if (e.coldstart) 
 
\t \t \t \t \t \t \t \t $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>'); 
 
\t \t \t \t \t \t \t else 
 
\t \t \t \t \t \t \t $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t \t \t 
 
\t \t \t \t \t \t $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>'); 
 
         //android only 
 
\t \t \t \t \t \t $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>'); 
 
         //amazon-fireos only 
 
         $("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp + '</li>'); 
 
        break; 
 
        
 
        case 'error': 
 
\t \t \t \t \t \t $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>'); 
 
        break; 
 
        
 
        default: 
 
\t \t \t \t \t \t $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>'); 
 
        break; 
 
       } 
 
      } 
 
      
 
      function tokenHandler (result) { 
 
       $("#app-status-ul").append('<li>token: '+ result +'</li>'); 
 
       // Your iOS push server needs to know the token before it can push to this device 
 
       // here is where you might want to send it the token for later use. 
 
\t \t \t \t alert(result); 
 
      } 
 
\t \t \t 
 
      function successHandler (result) { 
 
       $("#app-status-ul").append('<li>success:'+ result +'</li>'); 
 
      } 
 
      
 
      function errorHandler (error) { 
 
       $("#app-status-ul").append('<li>error:'+ error +'</li>'); 
 
      } 
 
      
 
\t \t \t document.addEventListener('deviceready', onDeviceReady, true); 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
    }, 
 
    // Update DOM on a Received Event 
 
    receivedEvent: function(id) { 
 
     var parentElement = document.getElementById(id); 
 
     var listeningElement = parentElement.querySelector('.listening'); 
 
     var receivedElement = parentElement.querySelector('.received'); 
 

 
     listeningElement.setAttribute('style', 'display:none;'); 
 
     receivedElement.setAttribute('style', 'display:block;'); 
 

 
     console.log('Received Event: ' + id); 
 
    } 
 
}; 
 

 
app.initialize();

В index.html я не делал каких-либо изменений ... просто добавил последний два .js файлы, как в примере, даже если index.html является почти пустой

<!DOCTYPE html> 
 
<!-- 
 
    Licensed to the Apache Software Foundation (ASF) under one 
 
    or more contributor license agreements. See the NOTICE file 
 
    distributed with this work for additional information 
 
    regarding copyright ownership. The ASF licenses this file 
 
    to you under the Apache License, Version 2.0 (the 
 
    "License"); you may not use this file except in compliance 
 
    with the License. You may obtain a copy of the License at 
 

 
    http://www.apache.org/licenses/LICENSE-2.0 
 

 
    Unless required by applicable law or agreed to in writing, 
 
    software distributed under the License is distributed on an 
 
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 
    KIND, either express or implied. See the License for the 
 
    specific language governing permissions and limitations 
 
    under the License. 
 
--> 
 
<html> 
 
    <head> 
 
     <!-- 
 
     Customize this policy to fit your own app's needs. For more guidance, see: 
 
      https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy 
 
     Some notes: 
 
      * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication 
 
      * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly 
 
      * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: 
 
       * Enable inline JS: add 'unsafe-inline' to default-src 
 
     --> 
 
     <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> 
 
     <meta name="format-detection" content="telephone=no"> 
 
     <meta name="msapplication-tap-highlight" content="no"> 
 
     <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> 
 
     <link rel="stylesheet" type="text/css" href="css/index.css"> 
 
     <title>Hello World</title> 
 
    </head> 
 
    <body> 
 
    <script type="text/javascript"> 
 
      // var pushNotification; 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t 
 
\t </script> 
 
     <div class="app"> 
 
      <h1>Apache Cordova</h1> 
 
      
 
     </div> 
 
     <script type="text/javascript" src="cordova.js"></script> 
 
     <script type="text/javascript" src="js/index.js"></script> 
 
     <script type="text/javascript" charset="utf-8" src="js/jquery_1.5.2.min.js"></script> 
 
     <script type="text/javascript" src="js/PushNotification.js"></script> 
 
    </body> 
 
</html>

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

Я также прочитал, что есть некоторые проблемы с pushplugin и iOS 8, не могу понять, были ли они решены или нет. Кто-нибудь может дать мне какое-нибудь предложение?

Спасибо

ответ

0

Ваш index.js это все хорошо, вы должны установить следующие вещи в вашем index.html:

1: Вы не должны inlcude PushNotifications.js по своему усмотрению, так что удалить
<script type="text/javascript" src="js/PushNotification.js"></script>, cordova.js автоматически включит все файлы js-модулей.

2: Включить скрипт jquery выше index.js.

3: В вас index.js вы следующий код

if (device.platform == 'android' || device.platform == 'Android' || 
          device.platform == 'amazon-fireos') { 

Это даст вам сообщение об ошибке, потому что device объект не определен, на самом деле это объект, который экспортируется из плагина устройства, поэтому установить этот plugin по команда
cordova plugin add cordova-plugin-device

4 запущенный: Кроме того, добавьте <ul id="app-status-ul"></ul> в вашем index.html, так что вы можете увидеть результаты.
Внесите эти изменения, и ваш код будет работать отлично.

+0

Большое спасибо за ваш ответ. Да, я уже добавил плагин для устройства, забыл сказать. Удалено PushNotification.js в index.html. Моя большая ошибка. Я забыл поставить предупреждение в функции errorHandler. Как только я это сделал, я заметил, что это проблема с профилем подготовки: Xcode загрузил общий, вместо этого AdHoc с моим сертификатом. Изменено теперь отображается токен устройства. – flauros

+0

Заметил, что оповещения Xcode для большого количества устаревших объектов в pushplugin.m для iOS 8 и iOS 7. Для этого я думаю, что мне придется обновлять файл, как я видел в некоторых сообщениях здесь. И когда я запускаю приложение на своем iphone, он работает правильно, но на Xcode я получаю это сообщение: «запуск процесса не завершен: время ожидания запуска приложения» и останавливает выполнение, даже если на устройстве приложение все еще работает. Если у вас есть идеи для этих проблем, я также принимаю предложения. – flauros

+0

Не уверен, но попробуйте 'cordova plugin add cordova-plugin-push-notification' вместо установки с git url. Для android он исправляет проблемы сборки, не знаю об ios. Но вы можете попробовать. –