iOS 本地通知

如果用户长时间没有使用我们的APP,我们就需要提醒用户来使用。这个本地通知就可以做到。

先说明一下我的解决思路:在AppDelegate里面写

1,当用户退出app时创建一个通知,一定时间后调用,比如10秒。

//进入后台响应的方法 
- (void)applicationDidEnterBackground:(UIApplication *)application
{

    // 初始化本地通知对象
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    if (notification) {
        // 设置通知的提醒时间
        NSDate *currentDate   = [NSDate date];
        notification.timeZone = [NSTimeZone defaultTimeZone]; // 使用本地时区
        notification.fireDate = [currentDate dateByAddingTimeInterval:10];
    
        
        // 设置提醒的文字内容
        notification.alertBody   = @"您一周都没有关注宝宝了,快来看看!";
        notification.alertAction = NSLocalizedString(@"关心宝宝", nil);
        
        // 通知提示音 使用默认的
        notification.soundName= UILocalNotificationDefaultSoundName;
        
        // 设置应用程序右上角的提醒个数
        notification.applicationIconBadgeNumber++;
        
        // 设定通知的userInfo,用来标识该通知
        
        NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:@"notification",@"nfkey",nil];
        [notification setUserInfo:dict];
        // 将通知添加到系统中
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

    
}

2,在收到通知,点击进入应用的时候取消通知,讲外面显示的数字赋值为0,application.applicationIconBadgeNumber=0;

didReceiveLocalNotification是app在前台运行,通知时间到了,调用的方法。如果程序在后台运行,时间到了以后是不会走这个方法的。

applicationDidBecomeActive是app在后台运行,通知时间到了,你从通知栏进入,或者直接点app图标进入时,会走的方法。

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    
    application.applicationIconBadgeNumber=0;
    
 
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    application.applicationIconBadgeNumber=0;
    //取消通知
    for (UILocalNotification *noti in [application scheduledLocalNotifications]) {
        NSString *notiID = [noti.userInfo objectForKey:@"nfkey"];
        
        if ([notiID isEqualToString:@"notification"]) {
            [application cancelLocalNotification:noti];
        
        }
    }
}

3,当用户在没收到通知进入应用的时候取消通知。原因:当你第一次退出程序,就会创建一个通知a,10秒后推送,如果在这10秒内,重新登录退出又会创建 新的通知b,那么我们会连续收到两个通知。为了避免重复,在通知a时间还没有到情况下登录app我们就取消通知a,退出时创建通知b。

- (void)applicationWillEnterForeground:(UIApplication *)application
{
  //取消所有通知
    [application cancelAllLocalNotifications];
    
}

如果想要重复调用这个通知,

// 设置重复间隔

 notification.repeatInterval = kCFCalendarUnitDay;
 
原文地址:https://www.cnblogs.com/6duxz/p/4185560.html