ios - 如何在每天的特定时间发送 localNotification,即使那个时间已经过去了?

标签 ios swift nsdate localnotification

我有这段代码每天早上 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/

相关文章:

javascript - React-Native - 错误 : `StackViewTransitionConfigs` has been removed

arrays - 将 RandomAccessSlice 转换为 RandomAccessCollection

ios - 在核心数据中存储 NSDate (swift)

Swift 根据时间戳显示时间或日期

ios - 以编程方式将音频文件保存到相册库 iPhone

ios - 如何在 iOS 中禁用导航栏

ios - UIAlertController 的呈现速度非常慢

ios - 尝试滑动删除当前单元格时,表格 View 单元格开始晃动

苹果手机SDK :how to convert arabic date format to english?

ios - 已加载 Nib 但未设置 'view' socket