Scheduling local notifications to repeat daily from tomorrow

602 Views Asked by At

I'm trying to schedule a local notification to fire every day, at a specific time, but from tomorrow.

e.g. "Trigger a notification every day at 2 pm, from tomorrow"

This is how I set up my schedule function.

func scheduleNotifications(date: Date, identfier: String, after: Bool) {
    
    let content = UNMutableNotificationContent()
    content.title = "App"
    content.body = "Test."
    content.sound = .default
    content.userInfo = ["Hour": Int(hourFormatter.string(from: date)) ?? 0]
    
    let afterDay = Calendar.current.date(byAdding: .day, value: after ? 1 : 0, to: Date())

    var components = Calendar.current.dateComponents([.hour, .minute], from: afterDay!)

    components.hour = Int(hourFormatter.string(from: date)) ?? 0
    components.minute = Int(minuteFormatter.string(from: date)) ?? 0
    
    
    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request)

}
1

There are 1 best solutions below

1
Gopi Donga On

This code is for daily notification just call it in tomorrow schedule time

func setupNotificationSettings() {

DispatchQueue.main.async {
    let content: UNMutableNotificationContent = UNMutableNotificationContent()
    
    content.title = AppName
    content.body = "APP_Body"
    content.sound = UNNotificationSound.default
    
    let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
    let request: UNNotificationRequest = UNNotificationRequest(identifier: "\(AppName)_Local", content: content, trigger: trigger)
    
    let center: UNUserNotificationCenter = UNUserNotificationCenter.current()
    center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
    center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
    center.add(request) { (error) in
        
    }
}
}