Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift Local notification not "popping up"

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!

like image 517
Chan Jing Hong Avatar asked Nov 13 '15 11:11

Chan Jing Hong


1 Answers

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

like image 151
JoGoFo Avatar answered Oct 13 '22 09:10

JoGoFo