0
votes

I am trying to add badge and sound to local notification in my app but I get none. I see the notification when it supposed to appear but without any sound or badge... Can anyone please tell me what I am doing wrong?

func requestUserPermissionForNotifications(){
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
        if (error != nil) {
            print("Error authorzing notifications")
        } else {
            if (didAllow) {
                self.setDailyNotifications()
                print("User allowed to Push notifications")
            } else {
                print("User did not allow to Push notifications")
            }
        }
    })
}

func setDailyNotifications() {
    var sunday = DateComponents()
    sunday.hour = 11
    sunday.minute = 00
    sunday.weekday = 1
    timeNotification(id: "Sunday", notificationTitle: "Daily reward is waiting", notificationText: "Log in and get your daily reward", timeOfNotification: sunday)
}

func timeNotification(id: String, notificationTitle: String, notificationText: String, timeOfNotification: DateComponents) {
    let trigger = UNCalendarNotificationTrigger(dateMatching: timeOfNotification, repeats: true)
    let content = UNMutableNotificationContent()
    content.title = notificationTitle
    content.body = notificationText
    content.sound = UNNotificationSound.default()
    content.badge = 1

    let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if (error != nil) {
            print("Error adding notification \(id) --- \(String(describing: error))")
        }
    }
}
1
Did you check Settings on your device? - Anton Belousov
I did, sounds and badges are allowed. - Nir.Hayun

1 Answers

0
votes

The issue was that I called my setDailyNotifications() function from the requestAuthorization() method. All I did was to call setDailyNotifications() from viewDidLoad if the user approved push notifications.