关于设置applicationIconBadgeNumber提醒数字的问题

在日常开发中,当我们需要设置appIcon右上角的提示数字时,难免会用到UIApplication的applicationIconBadgeNumber的属性,但是,也许有人比较粗心,没有仔细看完苹果官方给的代码注释,就会着急使用这个属性,但是呢,运行时会发先在控制台会打印一串英文异常:
Attempting to badge the application icon but haven’t received permission from the user to badge the……

原因是:

iOS8中要实现badge、alert和sound等都需要用户同意才能,因为这些都算做Notification“通知”,为了防止有些应用动不动给用户发送“通知”骚扰用户,所以在iOS8时,要“通知”必须要用户同意才行。
在iOS8中,设置应用的application badge value需要得到用户的许可。
如果把模拟器换成iOS7.1或者更早的,就不会有这个问题。

这时苹果官方提供的属性以及注释:

@property(nonatomic) NSInteger applicationIconBadgeNumber;  // set to 0 to hide. default is 0. In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to set the icon badge.

解决方法:
我们需要进行版本的判断,如果系统版本大于等于8.0的话,我们就在用户打开应用的时候弹出一个提示框提示说我们要发送通知给用户,如果用户同意,那么我们就可以了。而如果系统版本小于8.0的话,因为默认是可以的,所以我们不需要做任何事情。
如此,我们只要在AppDelegate.m中的 - (BOOL)application:(UIApplication
)application didFinishLaunchingWithOptions:(NSDictionary )launchOptions 的方法中进行版本判断即可。

代码如下:

#define kDeviceVersion  [[UIDevice currentDevice] systemVersion].floatValue
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    /**
     *  iOS8以后需要注册,才能将未读的数在图标右上角显示
     */
    if (kDeviceVersion >= 8.0) {
        // 使用本地通知 (本例中只是badge,但是还有alert和sound都属于通知类型,其实如果只进行未读数在appIcon显示,只需要badge就可, 这里全写上为了方便以后的使用)
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        // 进行注册
        [application registerUserNotificationSettings:settings];
    }

现在,将应用程序在后台运行,会发现appIcon右上角就会显示未读数了!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值