Search code examples
iosswiftnsnotificationcenterlocalnotification

How to repeat the LocalNotification only once in a day


I create a application in which application notify the users once in a day.

For that I used the following code

 func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {

    scheduleNoticaiftion()
}

// Schedule the Notifications with repeat
func scheduleNoticaiftion() {
    //UIApplication.sharedApplication().cancelAllLocalNotifications()

    // Schedule the notification ********************************************

        let notification = UILocalNotification()
        notification.alertBody = "Hey! Upload your latest photos"
        notification.soundName = UILocalNotificationDefaultSoundName
        notification.fireDate = NSDate()
       // notification.category = categoryID
        notification.repeatInterval = NSCalendarUnit.CalendarUnitDay

        UIApplication.sharedApplication().scheduleLocalNotification(notification)

}

The above code is working fine but the problem is if user opens and close(terminate) the app 6 time in a day.

User get total 6 notification on next day based on application open time i.e. if I open application in 3 p.m and close it and next open application at 4 p.m. it will show the notification in 3pm and 4pm of next day simultaneously.

Question: How can I send only one notification within 24 hours? i.e. If a user install my app at 4pm it will notify the user every day at 4pm ?


Solution

  • The operating system is responsible for delivering local notifications at their scheduled times. see UILocalNotification
    So operating system maintain the scheduledLocalNotifications count.

    func scheduleNotification() {
    
        if UIApplication.sharedApplication().scheduledLocalNotifications.count == 0 {
    
            let notification = UILocalNotification()
            notification.alertBody = "Hey! Update your counter ;)"
            notification.soundName = UILocalNotificationDefaultSoundName
            notification.fireDate = NSDate()
            notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
    
            UIApplication.sharedApplication().scheduleLocalNotification(notification)
        }
    }
    
    
    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        scheduleNotification()
    }