【问题标题】:iOS 10 Notification trigger and repeat every minuteiOS 10 通知触发并每分钟重复一次
【发布时间】:2017-02-01 15:22:39
【问题描述】:

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

【问题讨论】:

    标签: ios ios10 unusernotificationcenter


    【解决方案1】:

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

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

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

    【讨论】:

    • 这将在 2 分钟后开始,但不会每隔几分钟重复一次。
    【解决方案2】:

    当您收到远程推送通知时,您可以每 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()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 2012-02-08
      • 2021-04-05
      相关资源
      最近更新 更多