6

Ceci est un suivi de mon précédent posting sur StackOverflow. Il est préférable de commencer un nouveau message (puisque j'ai fait plus de progrès qu'auparavant) plutôt que d'ajouter une nouvelle question à un sujet précédent.Problème lors de l'envoi d'une notification Apple Push à l'aide de Java et REST

Am en utilisant la bibliothèque Javapns sur Google Code pour envoyer un Apple Push Notification via un service Web basé sur REST ...

Voici les étapes que j'ai terminé:

programme iPhone Developer Portal (IDPP):

(1) Création de l'ID d'application et du certificat SSL et des clés APNS.

(2) Création et installation du profil d'approvisionnement.

(3) Installation du certificat et de la clé SSL sur le serveur.

(4) Configurer mon application iPhone pour m'enregistrer pour les notifications à distance.

XCode:

a pu obtenir mon jeton appareil lorsque j'ai construit et déployé mon application sur mon appareil.

Dès que mon application iPhone s'est déployée, la boîte de dialogue est apparue sur mon iPhone indiquant que mon application souhaitait envoyer des notifications push et également demander la permission de les autoriser. Lorsque j'ai invoqué mon service Web, grâce à mes instructions Log4J, j'ai pu constater que mon service Web basé sur REST était effectivement appelé, mais je n'ai jamais reçu de notification push sur mon application iPhone!

ApnsManager classe:

public class ApnsManager { 

    /** APNs Server Host **/ 
    private static final String HOST = "gateway.sandbox.push.apple.com"; 

    /** APNs Port */ 
    private static final int PORT = 2195; 

    public void sendNotification(String deviceToken) 
    throws Exception { 
     try { 
      PayLoad payLoad = new PayLoad(); 
      payLoad.addAlert("My alert message"); 
      payLoad.addBadge(45); 
      payLoad.addSound("default"); 

      PushNotificationManager pushManager = 
       PushNotificationManager.getInstance(); 

      pushManager.addDevice("iPhone", deviceToken); 

      log.warn("Initializing connectiong with APNS..."); 

      // Connect to APNs 
      pushManager.initializeConnection(HOST, PORT, 
      "/etc/Certificates.p12", "password", 
      SSLConnectionHelper.KEYSTORE_TYPE_PKCS12); 

      Device client = pushManager.getDevice("iPhone"); 

      // Send Push 
      log.warn("Sending push notification..."); 
      pushManager.sendNotification(client, payLoad); 
      pushManager.stopConnection(); 
     } 
     catch (Exception e) { 
      e.printStackTrace("Unable to send push "); 
     } 
    } 
} 

Service Web RESTful:

@Path(ApnService.URL) 
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
public class ApnService { 
    public static final String URL = "/apns"; 

    @GET 
    @Path("send") 
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 
    public String send() throws JSONException, IOException { 
     String msg = ""; 

     try { 
      log.debug("Inside ApnService.send() method."); 
      log.debug("Sending notification to device"); 
      ApnManager.sendNotification("32b3bf28520b977ab8eec50b482 
      25e14d07cd78 adb69949379609e40401d2d1de00000000738518e5c 
      000000003850978c38509778000000000000000000398fe12800398f 
      e2e0398fe1040000"); 
     } catch(Exception e) { 
       e.printStackTrace(); 
       msg = "fail"; 
     } 
     msg = "success"; 

     StringWriter sw = new StringWriter(); 
     JsonFactory f = new JsonFactory(); 
     JsonGenerator g = f.createJsonGenerator(sw); 

     g.writeStartObject(); 
     g.writeStringField("status", msg); 
     g.writeEndObject(); 
     g.close(); 

     return sw.toString(); 
    } 
} 

Maintenant, quand je déploie mon application à mon serveur d'applications et d'ouvrir un client de repos et tapez:

http: // localhost: 8080/myapp/apns/envoyer

Le client reste retourne ceci:

HTTP/1.1 200 OK

Les messages journaux suivants sont émis à la console:

01:47:51,985 WARN [ApnsManager] Initializing connectiong with APNS... 
01:47:52,318 WARN [ApnsManager] Sending push notification... 

MyAppDelegate.m

- (void) applicationDidFinishLaunching : 
    (UIApplication*) application 
{ 
    NSLog(@"LAUNCH"); 

    // Configure REST engine 
    RESTAPI* api = [RESTAPI getInstance]; 
    [api setNetworkAddress:kLocalAddress port:kDefaultPort]; 

    UIRemoteNotificationType notificationTypes 
    = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound; 
    if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes] 
     != notificationTypes) { 
     NSLog(@"Registering for remote notifications..."); 
     [[UIApplication sharedApplication] 
     registerForRemoteNotificationTypes:notificationTypes]; 
    } else { 
     NSLog(@"Already registered for remote notifications..."); 
     // Uncomment this if you want to unregister 
     // NSLog(@"Unregistering for remote notifications..."); 
     // [[UIApplication sharedApplication] unregisterForRemoteNotifications]; 
    } 

mainWindow = [[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds] retain]; 
toolsNav = [[[ToolsNav alloc] init] retain]; 

[mainWindow addSubview:toolsNav.view]; 
[mainWindow makeKeyAndVisible]; 
} 

Cependant, je ne reçois pas la notification push sur mon application (résidant sur mon iPhone)!

suis vraiment déconcerté à ce moment ...

Que pourrais-je faire mal? :(

Est-il un problème avec la façon dont je mis en place mon service RESTful Web (désolé, je suis un débutant à REST)?

apprécierais vraiment si quelqu'un pouvait me aider dans cette ...

Merci de prendre le temps de lire ce ...

+0

La chaîne de jetons contient un espace. A-t-il été introduit lorsque vous avez copié le code ici? Essayez de le supprimer. – notnoop

+0

Salut Saeed ... Oui, l'espace de la chaîne symbolique a été introduit lorsque j'ai copié le code (et reformaté le code pour le rendre plus visuel ici). Dans mon code actuel, il n'y a pas d'espace. Je suis toujours coincé donc j'apprécierais que quelqu'un puisse m'aider avec ça. J'ai un peu de snitch en cours d'exécution et quand je lance le service web, il me demande si je souhaite me connecter au port 2195 et il envoie la notification push. Il n'apparaît tout simplement pas sur l'application de mon iPhone. Y a-t-il quelque chose que je fais de mal? Est-ce le code REST? –

+0

Vous devez également inclure le code pour les méthodes "Gestion des notifications distantes" de UIApplicationDelegate que vous avez implémenté. – bpapa

Répondre

5

découvert la solution! la chaîne de jeton de périphérique généré semblait trop long.

Mon NSData à code hexadécimal imprimait le jeton mauvais (il devrait être 64 caractères, avant qu'il ne soit de 155 caractères).

Solution:

- (NSString *)hexadecimalDescription 
{ 
    NSMutableString *string = [NSMutableString stringWithCapacity:[self length] * 2]; 
    const uint8_t *bytes = [self bytes]; 

    for (int i = 0; i < [self length]; i++) 
     [string appendFormat:@"%02x", (uint32_t)bytes[i]]; 

    return [[string copy] autorelease]; 
} 

Maintenant, je reçois les notifications sur mon appareil! :)

Bonne programmation à tous!

Questions connexes