Schedule local Notification after app was closed for 7 days

僤鯓⒐⒋嵵緔 提交于 2019-12-04 11:14:09

You should unschedule previous notification.

for (UILocalNotification *lNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) 
    {
        if ([[lNotification.userInfo valueForKey:@"information"] isEqualToString:@"Some information"])
        {
            [[UIApplication sharedApplication]cancelLocalNotification:lNotification];
            break;
        }
    }

Set fire date by below way:

NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *componentsForReferenceDate = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                     fromDate:[NSDate date]];
    [componentsForReferenceDate setHour: 17] ;
    [componentsForReferenceDate setMinute:30] ;
    [componentsForReferenceDate setSecond:00] ;

    NSDate *tempDate = [calendar dateFromComponents: componentsForReferenceDate];
    [componentsForReferenceDate release];

    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setDay:7];
    NSDate *fireDateOfNotification = [calendar dateByAddingComponents:comps
                                                               toDate:tempDate options:0]
    [comps release];

The notification.repeatInterval = NSWeekCalendarUnit is causing this. use:

notification.repeatInterval = 0;

This prevent repeating (source).

Here is the Swift 2.0 adaptation

Unscheduling the current notification

    for notifMe:AnyObject in UIApplication.sharedApplication().scheduledLocalNotifications!{
        let title = notifMe.userInfo["information"] as? String
        if title == "some information"{
                UIApplication.sharedApplication().cancelLocalNotification(notifMe as! UILocalNotification)
        }
        }

Setting the date for the notification

    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Month).union(NSCalendarUnit.Day),fromDate: date)
    components.hour = 17
    components.minute = 30
    components.second = 00

    let tempDate = calendar.dateFromComponents(components)!
    let comps = NSDateComponents()
    comps.day = 7
    let fireDateOfNotification = calendar.dateByAddingComponents(comps, toDate: tempDate, options:[])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!