特定时间的本地通知

Local Notifications at a specific time

我有一个应用程序,我需要在特定的日期和时间收到通知。我正在使用以下代码设置日期和时间。

let app = UIApplication.sharedApplication()

let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
app.registerUserNotificationSettings(notificationSettings)

let calendar = NSCalendar.currentCalendar()

let date = NSDateComponents()
date.hour = 5
date.minute = 0
date.month = 5
date.day = 21
date.year = 2016
date.timeZone = NSTimeZone.systemTimeZone()

let alarm = UILocalNotification()
alarm.fireDate = calendar.dateFromComponents(date)
alarm.timeZone = NSTimeZone.defaultTimeZone()
alarm.alertTitle = ""
alarm.alertBody = ""
alarm.soundName = "Sound.wav"
app.scheduleLocalNotification(alarm)

我允许通知,我可以在用户离开应用程序后十秒安排通知,但不是特定时间。

设置你的日期如下

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*find out and place date format from http://userguide.icu-project.org/formatparse/datetime*/
let customDate = dateFormatter.dateFromString(/*your_date_string*/)

// your code
 alarm.fireDate = customDate

your_date_string 将是您要安排通知的日期时间。

希望对您有所帮助!

除了一件事,你的代码是正确的,小时。 NSDate 在 24 小时系统上工作。因此,如果您希望在下午 5 点收到通知,您需要将小时值设置为 17

date.hour = 5 //this means 05:00 AM
date.minute = 0

date.hour = 17 //this mean 05:00 PM
date.minute = 0

P.S。 - 你的 alertBodyalertTitle 是空白的。您可能希望将其设置为某些内容以便显示。

希望这对您有所帮助。 :)