我有这段代码,它每天早上7点运行一个通知,它获取当前日期,然后在到达设定的时间时运行该通知,我的问题是,如果时间已经超过了设定的运行时间,那么它将每天在用户当前时间不是我早上7点的时间,这是我的代码
var dateFire: NSDateComponents = NSDateComponents() var getCurrentYear = dateFire.year var getCurrentMonth = dateFire.month var getCurrentDay = dateFire.day dateFire.year = getCurrentYear dateFire.month = getCurrentMonth dateFire.day = getCurrentDay dateFire.hour = 7 dateFire.minute = 0 dateFire.timeZone = NSTimeZone.defaultTimeZone() var calender: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! var date: NSDate = calender.dateFromComponents(dateFire)! var localNotification = UILocalNotification() localNotification.fireDate = date localNotification.alertBody = "A new day has begun and a fresh layer on snow lies on the mountain! Can you beat your highscore?" localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
如您所见NSCalendarUnit.CaldendarUnitDay,它每天早上7点运行。我不知道,即使时间是早上7点以后,通知在第二天仍将继续运行,将不胜感激
NSCalendarUnit.CaldendarUnitDay
更新了@ Paulw11对Swift 3.0的回答,并包装在一个函数中:
/// Set up the local notification for everyday /// - parameter hour: The hour in 24 of the day to trigger the notification class func setUpLocalNotification(hour: Int, minute: Int) { // have to use NSCalendar for the components let calendar = NSCalendar(identifier: .gregorian)!; var dateFire = Date() // if today's date is passed, use tomorrow var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire) if (fireComponents.hour! > hour || (fireComponents.hour == hour && fireComponents.minute! >= minute) ) { dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire); } // set up the time fireComponents.hour = hour fireComponents.minute = minute // schedule local notification dateFire = calendar.date(from: fireComponents)! let localNotification = UILocalNotification() localNotification.fireDate = dateFire localNotification.alertBody = "Record Today Numerily. Be completely honest: how is your day so far?" localNotification.repeatInterval = NSCalendar.Unit.day localNotification.soundName = UILocalNotificationDefaultSoundName; UIApplication.shared.scheduleLocalNotification(localNotification); }