I'm trying to send a local notification at scheduled time. But the notifications does not appear on the screen, but it is showing in the notification center when I swipe down.
This is what I'm trying to achieve This is what I getting.
This code is from my AppDelegate's didFinishLaunchingWithOptions().
// Setup local push notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
scheduleNotifications()
And this is the code for scheduleNotifications()
func scheduleNotifications() {
// create a corresponding local notification
let notification = UILocalNotification()
// Get today's date, time and year
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: NSDate())
// Sets the fire time to 2pm/1400 hours to anticipate user for lunch time
components.hour = 19
components.minute = 13
components.second = 00
notification.fireDate = components.date // Sets the fire date
notification.alertBody = "Enjoyed your lunch? Don't forget to track your expenses!"
notification.alertAction = "Add expense"
notification.repeatInterval = NSCalendarUnit.Day // Repeats the notifications daily
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
Any help would be appreciated. Thanks!
Your issue is the way you are converting the NSDateComponents object to an NSDate.
Simply calling components.date
without setting a calendar
for the NSDateComponents
object will return nil
.
Try using this instead:
notification.fireDate = calendar.dateFromComponents(components)
Alternatively, you can set the calendar
property on the components object:
components.calendar = calendar
Because you are setting the fireDate
property on the notification object to nil
, it will fire immediately, i.e. before you have a chance to close the app and lock the screen. This behavour is documented in the UILocalNotification class reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With