0

I want to shedule a daily notification on my app. But the poblem is while the app is open the notification does not appear and only if i exit the app the notification comes.

Note: I'm beginner on ios developement

My function:

func sheduleDailyLocalNotification() {
    
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: currentDate)
    let minute = calendar.component(.minute, from: currentDate)

    
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
        
        if success {
            
            let content = UNMutableNotificationContent()
            content.title = "iGrow Goals"
            content.subtitle = "Don't forget to check your today's goal steps"
            content.sound = UNNotificationSound.default
            
            // Configure the recurring date.
            var dateComponents = DateComponents()
            dateComponents.calendar = Calendar.current
            
            dateComponents.hour = hour
            dateComponents.minute = minute
            
            let trigger = UNCalendarNotificationTrigger(
                dateMatching: dateComponents, repeats: false)
            
            // choose a random identifier
            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
            
            // add our notification request
            UNUserNotificationCenter.current().add(request)
                            
        }else if let error = error {
            print(error.localizedDescription)
        }
        
    }
    
    
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
GSepetadelis
  • 272
  • 9
  • 24

1 Answers1

1

Sets the UNUserNotificationCenter delegate likes this (very early in your app lifetime):

let userNotificationCenter = UNUserNotificationCenter.current()
userNotificationCenter.delegate = self
// delegate must adopt UNUserNotificationCenterDelegate protocol

Then implement this method inside the UNUserNotificationCenter delegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.badge, .alert, .sound]) // Insert in the returned array what the app should handle
}

If a notification fires while your app is in the foreground, it is supposed that your app handles it (maybe with a custom behavior and interface), but implementing the above method you can trigger the default behavior.

Alain Bianchini
  • 3,883
  • 1
  • 7
  • 27