简体   繁体   English

如何更新IOS推送通知中的徽章编号?

[英]How to update the badge number in IOS push notification?

I recently use the Amazon SNS to push notification for my IOS app.我最近使用 Amazon SNS 为我的 IOS 应用程序推送通知。

It works well, the only problem I have encountered is when I receive the notification , the badge number will not be updated, here is how I implement:效果很好,我遇到的唯一问题是当我收到通知时,徽章编号不会更新,这是我的实现方式:

First I follow the example here https://aws.amazon.com/articles/9156883257507082 Here is the example code from the tutorial.首先我按照这里的示例https://aws.amazon.com/articles/9156883257507082这里是教程中的示例代码。

    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    application.applicationIconBadgeNumber = 0;
    NSString *msg = [NSString stringWithFormat:@"%@", userInfo];
    NSLog(@"%@",msg);
    [[Constants universalAlertsWithTitle:@"Push Notification Received" andMessage:msg] show];
}


-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Register for push notification
    application.applicationIconBadgeNumber = 0;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    if(launchOptions!=nil){
        NSString *msg = [NSString stringWithFormat:@"%@", launchOptions];
        NSLog(@"%@",msg);
        [[Constants universalAlertsWithTitle:@"Push Notification Received" andMessage:msg] show];
    }

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

    Message_BoardViewController *boardViewController = [Message_BoardViewController new];
    UINavigationController *navigationController = [UINavigationController new];

    navigationController.navigationBar.translucent = NO;

    [navigationController pushViewController:boardViewController animated:NO];
    [boardViewController release];

    self.window.rootViewController = navigationController;
    [navigationController release];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    [self.window makeKeyAndVisible];

    // Logging Control - Do NOT use logging for non-development builds.
#ifdef DEBUG
    [AmazonLogger verboseLogging];
#else
    [AmazonLogger turnLoggingOff];
#endif

    [AmazonErrorHandler shouldNotThrowExceptions];

    return YES;
}

As you can see, from the tutorial code it state如您所见,从教程代码中可以看出

application.applicationIconBadgeNumber = 0;

so obviously it will become 0 every time.所以很明显它每次都会变成0。

====================================================== ================================================== ====

I wonder what is the standard way to update the badge number ?我想知道更新徽章编号的标准方法是什么

Which appoarch is correct ?哪个方法是正确的?

1) Through programming like this application.applicationIconBadgeNumber = 0; 1) 通过像这样的编程application.applicationIconBadgeNumber = 0;

2) Or from the server payload like this? 2)或者像这样来自服务器有效载荷?

    $body = array(
'alert' => $message,
'sound' => 'sound.caf',
'badge' => $badge_count // Should be int type
);

======================================================== ================================================== ======

However, I found there is obstacle for each apporach , for the 1), the didReceiveNotification is not fire when the app is at background , so I can not do something like application.applicationIconBadgeNumber++;但是,我发现每个 apporach 都有障碍,对于 1),当应用程序处于后台时didReceiveNotification不会触发,因此我无法执行诸如application.applicationIconBadgeNumber++; to update the badge number.更新徽章编号。

for the 2) , the Amazon SNS service is only return对于 2) ,Amazon SNS 服务仅返回

$body = array(
'alert' => $message,
); 

and simply how can the server knows the badge number and add it at server payload, it seems I still need to post the update badge number to Amazon in didReceiveNotification and add it to payload.以及服务器如何知道徽章编号并将其添加到服务器有效负载中,似乎我仍然需要在didReceiveNotification中将更新徽章编号发布到亚马逊并将其添加到有效负载中。 But again, it does not call at background.但同样,它不会在后台调用。

Sorry for new to IOS progamming, would some experience programmer kindly guide me to implement the badge number update with push notification?对不起,IOS 编程新手,有经验的程序员可以指导我通过推送通知实现徽章编号更新吗? Thanks.谢谢。

You are supposed to send the badge number in the payload of the push notification.您应该在推送通知的有效负载中发送徽章编号。 Your server should set the badge count.您的服务器应该设置徽章计数。 This way the badge count will be updated regardless of whether the app is running or not running (and regardless of whether the user taps the notification to open the app or not).这样,无论应用程序是否正在运行(也无论用户是否点击通知以打开应用程序),徽章计数都会更新。 Your server should know what number to send.您的服务器应该知道要发送的号码。

And as to how your server is supposed to know what badge number to send - I don't know your app's logic, but lets take an email application as an example - suppose you want the badge number to show how many unread messages exist.至于您的服务器应该如何知道要发送的徽章编号 - 我不知道您的应用程序的逻辑,但让我们以电子邮件应用程序为例-假设您希望徽章编号显示存在多少未读消息。 The app should notify the server whenever a message is read, so the server can maintain the correct badge number for each user.应用程序应该在读取消息时通知服务器,以便服务器可以为每个用户维护正确的徽章编号。 This way, even if the user has multiple ways to access the data (iPhone app, iPad app, desktop browser, etc...), the server would know the current badge count and each device would show the correct badge count.这样,即使用户有多种方式访问​​数据(iPhone 应用程序、iPad 应用程序、桌面浏览器等),服务器也会知道当前的徽章计数,并且每个设备都会显示正确的徽章计数。

The application.applicationIconBadgeNumber = 0 is meant to clear the badge once the application is opened. application.applicationIconBadgeNumber = 0是为了在应用程序打开后清除徽章。 It should be done in both didReceiveRemoteNotification and didFinishLaunchingWithOptions , so that the badge number will always be cleared when the application is launched, or when the push notification is handled by the app.它应该在didReceiveRemoteNotificationdidFinishLaunchingWithOptions ,以便在应用程序启动时或应用程序处理推送通知时始终清除徽章编号。

You can do something like this.你可以做这样的事情。 Here I am using AWS Lambda and AWS SNS.我在这里使用 AWS Lambda 和 AWS SNS。

var params = {
'TargetArn' : 'Your Target Device',
'MessageStructure' : 'json',
'Message' : JSON.stringify({
  'default' : 'New Request from User',
  'APNS_SANDBOX' : JSON.stringify({
    'aps' : { 'alert' : 'New Request from User', 'badge':1,'category' : 'MESSAGE_CATEGORY' },
    'badge' : '1',
    'sound' : 'default',
    'attribute1' : "attribute 1 value",
    'attribute2' : "attribute 2 value",
    'attributeN' : "attribute N value"
  })
})
};

sns.publish(params, function(err, data) {
    if (err) {
        console.log(err.stack);
        return;
    }
    console.log('push sent');
    console.log(data);
    context.done(null, 'Function Finished!');  
});

ok I figure out how to use the badge number with Amazon SNS, if you publish your notification with PHP, then you can implement the badge like this好的,我想出了如何在 Amazon SNS 中使用徽章编号,如果您使用 PHP 发布通知,那么您可以像这样实现徽章

                        $sns->publish(array(
                        'MessageStructure' => 'json',
                        'TargetArn' => $endpointArn,
                        'Message' => json_encode(array(
                            'APNS_SANDBOX' => json_encode(array(
                                'aps' => array(
                                    'alert' => $push_message,
                                    'badge' => 1
                                )
                            ))
                        )),
                    ));

Just don't forget to set the badge to zero at your appdelegate.m , in the onReceive, onLaunchwithoption and onCompletefromBackground (Can't remember the excat spelling)只是不要忘记在您的 appdelegate.m 、 onReceive、onLaunchwithoption 和 onCompletefromBackground 中将徽章设置为零(不记得 excat 拼写)

Note that the key thing to recognise here is the property name in the JSON you send to AWS' SNS service.请注意,此处要识别的关键是您发送到 AWS 的 SNS 服务的 JSON 中的属性名称。 In your dev environment, you'll be sending through the APNS Sandbox, so you JSON will be like:在您的开发环境中,您将通过 APNS 沙箱发送,因此您的 JSON 将类似于:

{
    "default": "Test push-to-token notification.",
    "APNS_SANDBOX":"{\"aps\":{\"alert\":\"Test push-to-token notification.\",\"sound\":\"default\",\"badge\": 1}}",
    "GCM":"{\"data\":{\"body\":\"Test push-to-token notification.\",\"action_button_text\":\"OK\",\"sound\":\"default\"}}"
}

When you move into production, you need to changes the "APNS_SANDBOX" to just "APNS" .当您进入生产环境时,您需要将"APNS_SANDBOX"更改为"APNS" So like:所以像:

{
    "default": "Test push-to-token notification.",
    "APNS":"{\"aps\":{\"alert\":\"Test push-to-token notification.\",\"sound\":\"default\",\"badge\": 1}}",
    "GCM":"{\"data\":{\"body\":\"Test push-to-token notification.\",\"action_button_text\":\"OK\",\"sound\":\"default\"}}"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM