我想警告不要打电话
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:bg_NUM]
从
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
方法!
如果您计划的本地通知带有一些徽章编号,那么徽章将在进入 -didReceiveLocalNotification后的几毫秒内异步设置
样品:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// ^^^ maybe not reset badge to 0!! ^^^
}
另一个代码:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
sleep(1); //waiting for system is set our scheduled badge
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// ^^^ most chances for reset badge to 0 ^^^
}
测试代码,屏幕触摸安排本地通知并计算系统真实设置徽章之前的延迟:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
UILocalNotification *localNotif = [[[UILocalNotification alloc] init] autorelease];
localNotif.applicationIconBadgeNumber = rand()%100+1;
localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
[...]
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
while ([UIApplication sharedApplication].applicationIconBadgeNumber == 0) sleep(0);
NSLog(@"badge set: %d after %f sec.", [UIApplication sharedApplication].applicationIconBadgeNumber, CFAbsoluteTimeGetCurrent()-startTime);
}
输出:
badge set: 41 after 0.000839 sec.
badge set: 9 after 0.000754 sec.
badge set: 56 after 0.076026 sec.
badge set: 17 after 0.069889 sec.
badge set: 8 after 0.056245 sec.
badge set: 71 after 0.120729 sec.
badge set: 28 after 0.122720 sec.
badge set: 17 after 0.000758 sec.
此测试在不同设备上的 iOS 4.2/4.3/5.0/6.1
在 -didReceiveLocalNotification 消息中重置徽章编号时要小心!
(这仅适用于 LocalNotification /不是远程推送/并且仅当应用程序在接收时刻处于活动状态时)