Search code examples
iosiphoneswiftcocoa-touchuilocalnotification

UILocalNotification doesn't send


I'm trying to send a UILocalNotification like this:

func sendNotifiaction() {
        let notification = UILocalNotification()
        notification.userInfo = [
            "Identifier": self.identifier!
        ]
        notification.alertTitle = "Alarm!"
        notification.alertBody = "test"
        //notification.soundName = "Temporary-bleep-sound.aiff"
        notification.category = "category"

        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    }

I tried to put a break point on this method and it is being called and run, but the notification doesn't sent at all.

Anyone has an idea why?


Solution

  • You gotta to register the Notification first

    UIApplication.sharedApplication().cancelAllLocalNotifications()
    let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    

    Here's my demo for Notification firing at a specific time

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.
    
            UIApplication.sharedApplication().cancelAllLocalNotifications()
            let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    
            let localNotification1 = UILocalNotification()
            localNotification1.alertBody = "Your alert message at 9:00 pm"
            localNotification1.timeZone = NSTimeZone.defaultTimeZone()
            localNotification1.fireDate = self.getNinePMDate()
            UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)
            return true
        }
    
        func getNinePMDate() -> NSDate? {
            let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
            let now: NSDate! = NSDate()
            let date21h = calendar.dateBySettingHour(21, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)
            return date21h
        }
    }