Search code examples
iosswiftpush-notificationlocal

How to repeat local notification every 5 sec in background


Hi I want to show a notification for a call like WhatsApp I tried to make it via Timer but it didn't work

self.timer = Timer.init(timeInterval: 5.0, repeats: true, block: { (timer) in
DispatchQueue.main.async {                       
   self.scheduleLocalNotification(nameLocatino: myString)                                
}})

Solution

  • You have to use NSCalendarNotifiationTrigger

    Example for you

          var date = Date()
        let notificationCenter = UNUserNotificationCenter.current()
        for i in 0...10 {
        let content = UNMutableNotificationContent()
        content.title = "Title\(i)"
        content.body = "Body"
        var dateComponents = DateComponents()
        dateComponents.calendar = Calendar.current
        let secondsToAdd = 5
        dateComponents.second = secondsToAdd
        guard let futureDate = dateComponents.calendar?.date(byAdding: dateComponents, to: date),
            let futureDateComponents = dateComponents.calendar?.dateComponents([.day, .hour, .minute, .second], from: futureDate) else { return }
            date = futureDate
        print(futureDate)
        // Create the trigger as a repeating event.
        let trigger = UNCalendarNotificationTrigger(
            dateMatching: futureDateComponents, repeats: false)
        // Create the request
        let notificationIdentifier = "notification\(i)seconds" // you can use this indentifier if you want to cancel a notification
        let request = UNNotificationRequest(identifier: notificationIdentifier,
                                            content: content, trigger: trigger)
        // Schedule the request with the system.
        notificationCenter.add(request) { (error) in
            if error != nil {
                // Handle any errors.
            }
        }
    }
    

    where secondsToAdd is 5 so it calculates the upcoming date Above code will post 10 notification in 5 second interval You need to calculate the maximum time (last date entry) and schedule notification using the above code