使用 Java 和 REST 发送 Apple 推送通知时出现问题

发布于 2024-08-04 04:37:38 字数 4954 浏览 3 评论 0原文

这是我之前的帖子 在 StackOverflow 上。

我认为最好开始一个新的帖子(因为我比以前取得了更多的进步),而不是在之前的线程上附加一个新问题。

我正在使用 Google 代码上的 Javapns 库通过基于 REST 的网络服务发送 Apple 推送通知...

以下是我已完成的步骤:

iPhone 开发人员计划门户 (IDPP)

(1)创建了基于 App ID 和 APNS 的 SSL 证书和密钥。

(2) 创建并安装配置文件。

(3) 在服务器上安装SSL证书和密钥。

(4) 设置我的 iPhone 应用程序以注册远程通知。

XCode

当我构建应用程序并将其部署到我的设备上时,能够获取我的设备令牌。

一旦我的 iPhone 应用程序部署完毕,我的 iPhone 上就会出现一个对话框,表明我的应用程序想要发送推送通知,并且还请求允许它们的权限。

当我通过 Log4J 语句调用 Web 服务时,我能够看到基于 REST 的 Web 服务确实被调用,但我从未在 iPhone 应用程序上收到推送通知!

ApnsManager 类

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 服务

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

现在,当我将应用程序部署到应用程序服务器并打开休息客户端并输入:

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

其余客户端返回:

HTTP/1.1 200 OK

以下日志消息输出到我的控制台:

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

但是,我没有在我的应用程序(驻留在我的 iPhone 上)上收到推送通知!

我现在真的很困惑......

我可能做错了什么? :(

我设置 RESTful Web 服务的方式是否有问题(抱歉,我是 REST 的新手)?

如果有人可以帮助我,我将非常感激...

感谢您花时间阅读本文。 ..

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剧终人散尽 2024-08-11 04:37:38

发现了解决方案!生成的设备令牌字符串似乎太长。

我的 NSData 到十六进制代码打印了错误的标记(它应该是 64 个字符,之前是 155 个字符)。

解决方案

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

现在,我可以在我的设备上收到通知! :)

祝大家编程愉快!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文