如何在每个月的结束日通知通知消息

时间:2016-08-13 20:16:47

标签: ios objective-c appdelegate localnotification

如何通知每月通知。

-(void)applicationDidEnterBackground:(UIApplication *)application {

        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        format.dateFormat = @"dd-MM-yyyy";
        NSComparisonResult result = [[format stringFromDate:[NSDate new]] compare:[format stringFromDate:[self lastDayOfMonthOfDate:[NSDate date]]]];
        if (result == NSOrderedSame){
            if (![USERDEFAULTS boolForKey:@"IS_MONTH"]) {
                [self getNotifiedForEveryMonth:nil];
            }}
        else{
            [USERDEFAULTS setBool:NO forKey:@"IS_MONTH"];
        }
    }

// getNotifiedForEveryMonth

-(void)getNotifiedForEveryMonth:(id)userinfo{
        // Schedule the notification
    [USERDEFAULTS setBool:YES forKey:@"IS_MONTH"];
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = [NSDate date];
    localNotification.alertBody = @"Every Month Notificiation";
    localNotification.alertAction = @"Show me the item";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
 }

-(NSDate*)lastDayOfMonthOfDate:(NSDate *)date
{
        //    NSGregorianCalendar
    NSInteger dayCount = [self numberOfDaysInMonthCountForDate:date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comp = [calendar components:
                              NSCalendarUnitYear |
                              NSCalendarUnitMonth |
                              NSCalendarUnitDay fromDate:date];
    [comp setDay:dayCount];
    return [calendar dateFromComponents:comp];
}

-(NSInteger)numberOfDaysInMonthCountForDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:TIME_ABSOLUTE]];
    NSRange dayRange = [calendar rangeOfUnit:NSCalendarUnitDay
                                      inUnit:NSCalendarUnitMonth
                                     forDate:date];
    return dayRange.length;
}

以上代码我尝试通知通知。 它每个月都会收到通知,

如果用户关闭通知,然后下个月就会通知通知。

安装应用程序后,如何在月末结束通知用户通知消息。

感谢您的投入。

1 个答案:

答案 0 :(得分:0)

1)如果您希望每个月都有火警通知,即使用户没有超过月份开启应用,您也应该设置多个通知(最多60个)。例如,设置下个月的通知。

2)您应该通过此代码设置通知(在循环中,12次):

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

3)在设置新通知之前,请使用以下代码删除旧通知:

[[UIApplication sharedApplication] cancelAllLocalNotifications];