Reputation: 851
I have an app and I need to have the notifications at a specific date and time. I am using the following code to set the date and 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)
I have allowed notifications and I can schedule ten seconds after the user leaves the app but not for a specific time.
Upvotes: 1
Views: 2567
Reputation: 853
You code is correct except for one thing, the hour. NSDate works on 24-hour system. So if you want the notification to come on 5 PM you need to set the hour value to 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. - Your alertBody
and alertTitle
are blank. You might want to set it to something so that it shows up.
Hope this helps. :)
Upvotes: 3
Reputation: 328
Set your Date as below
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 will be the date&time when you want to schedule the notification.
Hope this Helps!
Upvotes: -1