应用程序在后台时如何增加徽章数量

Posted

技术标签:

【中文标题】应用程序在后台时如何增加徽章数量【英文标题】:How to increase badge number when application is in background 【发布时间】:2014-02-24 07:22:55 【问题描述】:

我正在使用此代码。当推送通知到来时,一切正常,但当应用程序处于后台时,徽章数量不会增加。如何解决这个问题呢?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    // Override point for customization after application launch.

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

    //UIApplication *application = [UIApplication sharedApplication];
    NSInteger badgeNumber = [application applicationIconBadgeNumber];// Take the current badge number
    //badgeNumber--;    // decrement by one
    [application setApplicationIconBadgeNumber:[[[launchOptions valueForKey:@"aps"]valueForKey:@"badge"]integerValue]];  // set ne badge number

    NSLog(@"userInfo :%@  %d",launchOptions,[[[launchOptions valueForKey:@"aps"]valueForKey:@"badge"]integerValue]);


    return YES;

【问题讨论】:

您必须在服务器上跟踪徽章编号。无法通过推送通知自动增加数字。如果 Apple 可以添加该功能,那就太棒了。 可以查看***.com/a/23948633/2246798 【参考方案1】:

当应用处于后台或关闭状态时,您无法使用代码增加徽章数量​​strong>。但可以通过通知负载中的值增加徽章。无代码将在此状态下执行,推送通知由操作系统本身处理。 This link 有同样的问题并已解决。

检查推送通知负载是否包含应用程序徽章字段并设置为大于0的值。如果为0,则当应用程序在后台或关闭时徽章编号将为0。

【讨论】:

【参考方案2】:

当应用程序在后台时,didFinishLaunchingWithOptions 方法永远不会调用。为了在您的应用程序处于后台时执行某些操作,您需要在 AppDelegate's applicationDidEnterBackground: 方法中实现您的逻辑。

- (void)applicationDidEnterBackground:(UIApplication *)application

[UIApplication sharedApplication].applicationIconBadgeNumber = 2;

【讨论】:

我正在从服务器获取徽章编号,当推送通知到来时如何增加?我想做whats app。 好的,我遇到了同样的情况,我通过下面的通知解决了这个问题,我的代码可能会对你有所帮助:NSDictionary *userInfo = [responseObject objectForKey:@"unread_notifications"]; [[NSNotificationCenter defaultCenter] addObserver:self 选择器:@selector(newNotification:) name:@"unread_notifications" object:nil]; -(void)newNotification:(NSNotification *) 通知 NSDictionary *userInfo = notification.userInfo; if ([[NSString stringWithFormat:@"%@",userInfo] isEqualToString:@"0"]) _notifiImageView.hidden = YES; _notificatinLbl.hidden = 是; 否则_notifiImageView.hidden = 否; _notificatinLbl.hidden = 否; _notificatinLbl.text = [NSString stringWithFormat:@"%@",userInfo]; NSString * 徽章 = [NSString stringWithFormat:@"%@",userInfo]; [UIApplication sharedApplication].applicationIconBadgeNumber = badge.intValue; 如果您还有其他问题,请告诉我?【参考方案3】:

当您发送推送通知时,您需要添加徽章值。因此,您需要为每个用户设备处理徽章。在php中是这样的:

$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge'=> 10
);

其中 10 就是图标中显示的数字。

【讨论】:

以上是关于应用程序在后台时如何增加徽章数量的主要内容,如果未能解决你的问题,请参考以下文章

当应用程序在Phonegap(cordova)的后台状态下收到推送通知时增加徽章编号,

如何在后台的android应用程序图标上计算推送通知消息徽章

应用程序在后台时如何更新徽章编号[重复]

在没有后台任务的情况下增加徽章值

如何在滚动时一一删除徽章数量

Usernotification 框架徽章不增加