Search code examples
iosswiftnotificationsnstimer

Repeat some action every x minutes between "A" a.m. and "B" p.m


How can I run for example local notifications? In UNUserNotificationCenter there is not repeat feature. Maybe using NSTimer or something like this?

Why my code does not work as I expected

let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    for hour in hours {
        for minute in stride(from: 0, to: 60, by: 5){
            let content = UNMutableNotificationContent()
            content.title = "Title"
            content.body = "Body"

            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request) { (error : Error?) in
                if let theError = error {
                    print(theError.localizedDescription)
                }
            }

        }
    }

Solution

  • There is a repeat feature.

    From Apple's documentation:

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: 
               "Hello!", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: 
               "Hello_message_body", arguments: nil)
    
    // Deliver the notification in five seconds and repeat it
    content.sound = UNNotificationSound.default() 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, 
            repeats: true)
    
    // Schedule the notification.
    let request = UNNotificationRequest(identifier: "60_seconds", content: content, trigger: trigger) 
    let center = UNUserNotificationCenter.current()
    center.add(request, withCompletionHandler: nil)
    

    Edit:

    As also written in the documentation, you certainly have to have user permissions to post notifications:

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization
    }
    

    Result:

    Notification is posted every minute: