本地通知·

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
    {
    /

    本地通知的应用场景:
    1.闹铃类的应用
    2.简单地单机游戏,比如开心农场
    3.阅读或者小说类的应用
    */
    //在iOS8之后,推送接收不到消息,需要我们手动设置
    float systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (systemVersion >= 8.0)
    {
    //设置推送的类型
    UIUserNotificationType type = UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;
    //将设置的类型添加到设置对象里面
    UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
    //将设置的内容添加到系统管理里面
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    //创建一个本地通知任务
    [self createLocalNotification];
    //取消本地通知任务
    [self cancelLocalNotification];
    return YES;
    }

#pragma mark - 处理小红点的个数

//接收到本地通知任务之后所做的操作
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
     notification.applicationIconBadgeNumber = 0;
}
//应用将要进入前台的时候
- (void)applicationWillEnterForeground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
}

#pragma mark - 取消本地通知任务

-(void)cancelLocalNotification
{
    //方式一:直接取消全部的通知任务
    //[[UIApplication sharedApplication]cancelAllLocalNotifications];
    //方式二:取消指定条件下的通知任务
    //首先获取系统管理里面全部的通知任务
    NSArray * notifications = [[UIApplication sharedApplication]scheduledLocalNotifications];
    for (UILocalNotification * noti in notifications) 
    {
         //通过条件判断,取消指定条件下的通知任务
         if ([noti.alertBody isEqualToString:@""]) 
         {
              [[UIApplication sharedApplication]cancelLocalNotification:noti];
              //处理小红点的数目
              noti.applicationIconBadgeNumber = 0;
          }
     }
}

#pragma mark - 创建本地通知任务

-(void)createLocalNotification
{
    //创建对象
    UILocalNotification * localNotification = [[UILocalNotification alloc]init];
    //设置推送时间,从当前时间开始计算多长时间之后开始推送
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    //设置推送重复的周期,相隔多长时间推送一次
    localNotification.repeatInterval = NSCalendarUnitHour;
    //设置推送的时区,使用默认的时区
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    //设置需要推送的内容
    localNotification.alertBody = @"亲~~~不要忘了吃药,千万不要放弃治疗";
    //设置推送消息时的音效
    localNotification.soundName =@"音效.caf";
    //设置接收到消息之后的小圆点数目
    localNotification.applicationIconBadgeNumber = 1;
    //将本地通知任务添加到系统管理里面
    [[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
}

你可能感兴趣的:(本地通知·)