I have a function which runs every 5 seconds to check for new messages, if a new message is triggered I'm updating the badge value of the tab bar item using the below code
NSString *chkUrl = @"http://domain.com/script.php";
NSURL *url = [[[NSURL alloc] initWithString:chkUrl] autorelease];
NSError *error = nil;
NSStringEncoding encoding;
NSString *returnHTML = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&encoding error:&error];
int totalNewMessages = [[returnHTML stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] intValue];
AppDelegate *mainDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"badge before:%@",[[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue);
[[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue = [NSString stringWithFormat:@"%d",totalNewMessages];
NSLog(@"badge after:%@",[[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue);
The problem is the badge value is not updating immediately! Maybe in the third of fourth call it will be updated! Anything wrong I'm doing! Or is it a bug in iOS!
As a work around, I repeated the above line 10 times on every update, but again it's not updating, so the problem is a delay in updating the badge value, it's not a matter of re-run the update line!
BTW, this problem is taking place in both Xcode 4.6 Simulator & my iPhone 5 with iOS 6.1
I Found the problem :)
My function that was running every 5 seconds was inside the below code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
[self checkNewMessages];
});
When I changed it to the below, it worked like a charm!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self checkNewMessages];
});
});