在通知回调中设置时,徽章未出现在选项卡栏项目上

Badge not appearing on tab bar item when set in notification callback

当我的应用收到通知时,我正在尝试将我的标签栏中的徽章设置为第 4 个标签上的“1”。奇怪的是,我的控制台显示该方法正在触发(请参阅 NSLog "Fire!"),但是一旦收到通知,徽章不会出现在我的标签栏项目上?我错过了什么吗?

AppDelegate.m

-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo 

    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        NSLog(@"App notification received!");
        // do stuff when app is active

    }else{
        // do stuff when app is in background

        static int i=1;
        [UIApplication sharedApplication].applicationIconBadgeNumber = i++;

        NSLog(@"App notification received background!");
    }
}

ViewController.m

- (void) myNotificationReceived:(NSNotification *) notification {


    [[self.tabBarController.tabBar.items objectAtIndex:3] setBadgeValue:@"1"];


    NSLog(@"Fire!");
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationReceived:) name:@"pushNotification" object:nil];

}

[[self.tabBarController.tabBar.items objectAtIndex:0] setBadgeValue:nil];将您的计数或数字设置为 nil 以显示在标签栏上

试试这个可能对你有帮助

不需要 NSNotification 方法 - 以下解决了 AppDelegate.m 中的问题:

-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {

    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo];

        UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
        [[tabController.viewControllers objectAtIndex:4] tabBarItem].badgeValue = @"1";


        NSLog(@"App notification received!");
        // do stuff when app is active

    }else{


        static int i=1;
        [UIApplication sharedApplication].applicationIconBadgeNumber = i++;

        //  NSLog(@"App notification received!");

        NSLog(@"App notification received background!");
    }
}