IOS Swift Local notification does not "pop up",

I am trying to send a local notification at a scheduled time. But notifications do not appear on the screen, but appear in the notification center when I scroll down.

This is what I am trying to achieve. This is what I get.

This code is from my AppDelegate 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 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 greatly appreciated. Thanks!

+6
source share
3 answers

Your problem is how you convert the NSDateComponents object to NSDate.

Just calling components.date without setting a calendar for the NSDateComponents object returns nil .

Try using this instead:

  notification.fireDate = calendar.dateFromComponents(components) 

Alternatively, you can set the calendar property on the component object:

 components.calendar = calendar 

Since you set the fireDate property of the notification object to nil , it fires immediately, i.e. before you can close the application and lock the screen. This behavior is described in reference to the UILocalNotification class.

+4
source

I get the same weird behavior. Just created a new project to test your code.

What I noticed when you change your FireDate to:

 notification.fireDate = NSDate(timeIntervalSinceNow: 10) 

You will get the desired behavior.

Hope this helps a bit!

+1
source

Check Settings> Answering machines> Notifications .

Check permissions there.

enter image description here

0
source

All Articles