0

I want to trigger the notification in 2 minutes time from now and also want to repeat it in every minute. The problem with the following code is it will repeat in every minute but it will start immediately not in 2 minutes. Appreciate any help.

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Good morning";
content.body = @"Body";
content.sound = [UNNotificationSound defaultSound];

UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:120];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]
                                 components:NSCalendarUnitSecond fromDate:date];

UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:YES];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"notification.daily" content:content trigger:trigger];

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    NSLog(@"Error:%@", error);
}];
Viraj
  • 209
  • 1
  • 2
  • 11

2 Answers2

0

Why are you not using UNTimeIntervalNotificationTrigger instead of UNCalendarNotificationTrigger.

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:120 repeats:YES];

Hope this answer will helpful.

Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
0

When you received Remote push notification, you can repeat it after every 2 minutes

Use below methods to do it.

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let action = response.actionIdentifier
        let request = response.notification.request
        let content = request.content
        if action == "snooze.action"{
            let snoozeTrigger = UNTimeIntervalNotificationTrigger(
                timeInterval: 120.0,
                repeats: true)
            let snoozeRequest = UNNotificationRequest(
                identifier: "snooze",
                content: content,
                trigger: snoozeTrigger)
            center.add(snoozeRequest){
                (error) in
                if error != nil {
                    print("Snooze Request Error: \(String(describing: error?.localizedDescription))")
                }
            }
        }
        completionHandler()
    }
Sunil Targe
  • 7,251
  • 5
  • 49
  • 80