Problem sending Apple Push Notification using Java and REST

10,669

Discovered the solution! The generated device token string seemed too long.

My NSData to hex code was printing the wrong token (it should be 64 characters, before it was 155 characters).

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];
}

Now, I am receiving the notifications on my Device! :)

Happy programming to all!

Share:
10,669
mw_javaguy
Author by

mw_javaguy

Updated on June 09, 2022

Comments

  • mw_javaguy
    mw_javaguy almost 2 years

    This is a follow up to my previous posting on StackOverflow.

    Figured its better to start a new post (since I made more progress than before) rather than appending a new question on a previous thread.

    Am using the Javapns library on Google Code to send an Apple Push Notification through a REST based web service...

    Here are the steps that I have completed:

    iPhone Developer Program Portal (IDPP):

    (1) Created the App ID and APNS based SSL Certificate and Keys.

    (2) Created and installed the provisioning profile.

    (3) Installed the SSL Certificate and Key on the server.

    (4) Set up my iPhone app to register for remote notifications.

    XCode:

    Was able to obtain my device token when I built and deployed my app onto my device.

    As soon as my iPhone app deployed, the dialog came up on my iPhone indicating that my app would like to send push notifications and also asked for permission to allow them.

    When I invoked my web service, through my Log4J statements, I was able to see that my REST based web service was indeed invoked but I never received a push notification on my iPhone app!

    ApnsManager class:

    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 ");
           }   
        }
    }
    

    RESTful Web Service:

     @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();
         }
    }
    

    Now, when I deploy my app to my app server and open up a rest client and type in:

    http: // localhost:8080/myapp/apns/send

    The rest client returns this:

    HTTP/1.1 200 OK

    The following log messages are outputted to my 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];
    } 
    

    However, I don't receive the push notification on my app (residing on my iPhone)!

    Am really stumped at this point...

    What could I possibly be doing wrong? :(

    Is it a problem with the way I set up my RESTful web service (sorry I am a newbie to REST)?

    Would really appreciate it if someone could assist me with this...

    Thank you for taking the time to read this...