1. iOS 8角标显示须要用户授权,可在应用启动时请求授权:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert; UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; } else { UIRemoteNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert; [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types]; } return YES; }
2. 显示角标:
- (void)showBadgeNumbers { // Request Method(服务器返回指定数据datas) // 若无新数据 if ([datas isEqualToString:@"0"]) { [self cleanBadgeNumber]; } else { // tabBarItem右上角显示未读数 self.tabBarItem.badgeValue = datas; // 应用右上角显示应用未读数 [UIApplication sharedApplication].applicationIconBadgeNumber = datas.intValue; } }
3. 清空角标:
- (void)cleanBadgeNumber { // tabBarItem右上角显示未读微博数 self.tabBarItem.badgeValue = nil; // 应用右上角显示应用未读微博数 [UIApplication sharedApplication].applicationIconBadgeNumber = 0; }
4. 设置定时器自动调用
- (void)viewDidLoad { [super viewDidLoad];// 显示未读数 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(showBadgeNumbers) userInfo:nil repeats:YES]; // 加入Runloop [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; }
5. 应用进入后台继续调用
- (void)applicationDidEnterBackground:(UIApplication *)application { // 向操作系统申请后台运行资格, 后台运行时间受系统控制 __block UIBackgroundTaskIdentifier taskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ // 后台运行时间已经结束 // 结束任务 [application endBackgroundTask:taskIdentifier]; }]; }
时间: 2024-10-02 00:12:16