Search code examples
iosswiftuilocalnotification

Local notifications firing immediately instead of when they are scheduled


I've been trying to schedule local notifications by weekday, but they seem to be firing immediately instead of when I schedule them. This is my code in AppDelegate in didFinishLaunchingWithOptions:

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
        var notification = UILocalNotification()
        var components = NSDateComponents()
        var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
        components.weekday = 5
        components.hour = 9
        components.minute = 24
        notification.alertBody = "Notification test"
        notification.fireDate = calendar?.dateFromComponents(components)
        UIApplication.sharedApplication().scheduleLocalNotification(notification)

Any clues on why it might not be working?


Solution

  • As others have mentioned, make sure to specify the year and month properties of the components object.

    components.year = 2016
    components.month = 6
    

    Part of the current fire date of your code is the following:

    0001-01-01
    

    Which means the notification will be fired at year "1" in January, not in 2016.