首页 文章

iOS 10通知触发并每分钟重复一次

提问于
浏览
0

我希望在2分钟后触发通知,并且还想在每分钟重复一次 . 以下代码的问题是它会在每分钟重复,但它会在2分钟内立即开始 . 感谢任何帮助 .

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);
}];

2 回答

  • 0

    为什么不使用 UNTimeIntervalNotificationTrigger 而不是 UNCalendarNotificationTrigger .

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

    希望这个答案会有所帮助 .

  • 0

    收到远程推送通知后,您可以在每2分钟后重复一次

    使用以下方法来执行此操作 .

    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()
        }
    

相关问题