Search code examples
swiftnotificationsuilocalnotificationlocalnotification

Notification willPresent won't calling when app is closed


I'm trying to notify user only in weekdays and don't want to do it with for loop so the notification has repeats bool as true. While app is open the willPresent function works but when app enters background the willPresent function doesn't called by app and sends notification to user in weekends which is i don't want to.

I already set the UNUserNotificationCenter.current().delegate = self at didFinishLaunchingWithOptions

Here is my willPresent Function in my AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let date = Date()
        var dayOfWeek = date.getWeekDay()
        if dayOfWeek.rawValue == 1 || dayOfWeek.rawValue == 7{
            print("Don't send a notification")
            completionHandler([])
        }else{
            completionHandler([.alert, .sound, .badge])
        }
    }

The Extension i'm using :

extension Date {

    enum WeekDay: Int {
        case sunday = 1
        case monday
        case tuesday
        case wednesday
        case thursday
        case friday
        case saturday
    }

    func getWeekDay() -> WeekDay {
        let calendar = Calendar.current
        let weekDay = calendar.component(Calendar.Component.weekday, from: self)
        return WeekDay(rawValue: weekDay)!
    }
}

Any help would be greatly appreciated. Thanks


Solution

  • That's because you should use didReceive method for receiving background notifications