Search code examples
iosswiftios-simulatorios9uilocalnotification

Local notification not working with iOS simulator


I'm not sure what I'm doing wrong. I have the following code:

//Create date
let calendar = NSCalendar.currentCalendar()
let now = NSDate()

let dateComponents = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: now)

dateComponents.minute += 2 //add 2 minutes to current time for debug

let date = calendar.dateFromComponents(dateComponents)

//Create notification
let notification = UILocalNotification()
notification.alertBody = "Your task is now available"
notification.alertAction = "open"
notification.fireDate = date
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["id": NSUUID().UUIDString]
notification.category = "Notification"
     UIApplication.sharedApplication().scheduleLocalNotification(notification)

When I place a breakpoint in application: didReceiveLocalNotification in app delegate, it never gets called.


Solution

  • Ok, I'll answer my own question. In AppDelegate: didFinishLaunchingWithOptions, I had to register notifications like so:

    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)