我有这段代码每天早上 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 点之后,通知仍然会在第二天运行,将不胜感激
最佳答案
swift 5.1
例如,这个每天早上 8:00 触发。 :
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Title"
notificationContent.body = "This is a test"
notificationContent.badge = NSNumber(value: 1)
notificationContent.sound = .default
var datComp = DateComponents()
datComp.hour = 8
datComp.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: datComp, repeats: true)
let request = UNNotificationRequest(identifier: "ID", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
关于ios - 如何在每天的特定时间发送 localNotification,即使那个时间已经过去了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31821339/