仅触发最后添加的通知

Only last added notification gets triggered

我正在为我的类似闹钟的应用更新 UNUserNotification 框架的通知,我以为我成功了,但我意识到当我设置多个闹钟时我只得到最新的通知。重复的日子正在努力。 会不会是触发器标识符的问题,它正在获取与以前的字符串相同的字符串并覆盖它? 我真的不明白这种行为,我找不到问题出在哪里。

这是代码:

func setRouteNotification(_ date: Date, onWeekdaysForNotify weekdays:[Int], snoozeEnabled:Bool,  onSnooze: Bool, soundName: String, routeName: String, index: Int) {
    configureCategory()
    // Notification content
    let routeCheckNotificationContent = UNMutableNotificationContent()
    let datesForNotification = correctDate(date, onWeekdaysForNotify: weekdays)
    routeCheckNotificationContent.title = "Hello!! Are you ready to cycle?"
    routeCheckNotificationContent.body = "Check route for alerts?"
    routeCheckNotificationContent.categoryIdentifier = Id.notificationCategory
    routeCheckNotificationContent.sound = UNNotificationSound.init(named: soundName + ".mp3")

    let repeating: Bool = !weekdays.isEmpty
    routeCheckNotificationContent.userInfo = ["snooze" : snoozeEnabled, "index": index, "soundName": soundName, "routeName": routeName, "repeating" : repeating]
    //repeat weekly if repeat weekdays are selected
    //no repeat with snooze notification
    if !weekdays.isEmpty && !onSnooze{ }

    syncAlarmModel()
    var counter = 1

    for d in datesForNotification {
        if onSnooze {
            alarmModel.alarms[index].date = Scheduler.correctSecondComponent(date: alarmModel.alarms[index].date)
        } else {
            alarmModel.alarms[index].date = d
        }

        // Notification trigger
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: d)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

        // Notification Request
        let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)

        // Add request
        UNUserNotificationCenter.current().add(routeNotificationRequest) { (Error) in
            if Error != nil {
                print("something went wrong with adding notification")
            }
        }
        print("added request\(alarmModel.alarms.count + weekdays.count + counter)")
        scheduledNotifications.append(counter)
        print("scheduled notifications are \(scheduledNotifications.count)")
        counter = ( counter + 1 )
    }
    print(alarmModel.alarms)
}

知道为什么不设置所有已编程的通知吗? 像往常一样非常感谢。

编辑:

我尝试设置一个数组 var scheduledNotifications: [Int] = [] 在添加通知时存储一个累进数字,并将其用作请求的标识符

let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)

所以我确定所有添加的通知都有一个唯一的请求标识符,但没有任何改变,仍然只收到最新的通知。

编辑 2: 当我为每天设置 2 个通知时的控制台输出:

added request9B642AB7-D4F3-4BDA-A5B3-D259419390D5
scheduled notifications are 1
added requestBA0EF286-CD4D-408D-AEFC-E3DED24FBBB4
scheduled notifications are 2
added request947FEFEF-0B4E-4163-8435-DCEC725F21F7
scheduled notifications are 3
added request8FF19184-F970-45AD-95FE-39CFABF83348
scheduled notifications are 4
added requestA447CABF-AD80-4A73-B214-B8A1AA47F76B
scheduled notifications are 5
added request217EF2E4-6241-4840-9431-16744F2E5314
scheduled notifications are 6
added request28C92EF2-143C-4364-9CC3-EB5335AA9B6F
scheduled notifications are 7
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-09-23 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-30 13:28:00 +0000, 2018-10-01 13:28:00 +0000, 2018-10-02 13:28:00 +0000, 2018-10-03 13:28:00 +0000, 2018-10-04 13:28:00 +0000, 2018-10-05 13:28:00 +0000, 2018-10-06 13:28:00 +0000]
added request2467230C-BC4A-4307-A0FA-108C5C291DCC
scheduled notifications are 8
added requestF27D9E76-BCCC-4E3A-91D7-CA60E64B61B9
scheduled notifications are 9
added requestDFF37582-AB57-4029-A480-6FFA4068E316
scheduled notifications are 10
added requestBC5633BD-234C-4555-8259-988908B6E4DA
scheduled notifications are 11
added requestEC35384F-2E7F-4267-A745-777E0C2A2CE8
scheduled notifications are 12
added requestFF866674-ED94-4BA0-8BA5-E8314521EA4F
scheduled notifications are 13
added request4D739860-83CB-43F9-895D-2E8D48C5154E
scheduled notifications are 14
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-10-06 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-23 13:29:00 +0000, 2018-10-01 13:29:00 +0000, 2018-10-02 13:29:00 +0000, 2018-10-03 13:29:00 +0000, 2018-10-04 13:29:00 +0000, 2018-10-05 13:29:00 +0000, 2018-10-06 13:29:00 +0000]
2018-09-23 15:27:12.771112+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57
2018-09-23 15:27:12.771425+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57

我使用当前日期(以秒为单位)作为标识符,它对我来说效果很好,如下所示:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UNUserNotificationCenter.current().requestAuthorization(options: []) { (granted, error) in


        if granted {

            let routeCheckNotificationContent = UNMutableNotificationContent()
            routeCheckNotificationContent.title = "Hello!! Are you ready to cycle?"
            routeCheckNotificationContent.body = "Check route for alerts?"
            routeCheckNotificationContent.categoryIdentifier = "\(Date().timeIntervalSince1970)"
            routeCheckNotificationContent.sound = UNNotificationSound.default()

            routeCheckNotificationContent.userInfo = ["snooze" : false, "index": 1, "soundName": "1", "routeName": "hmm", "repeating" : true]


            self.addNotification(content: routeCheckNotificationContent, date: Date().addingTimeInterval(30))
            self.addNotification(content: routeCheckNotificationContent, date: Date().addingTimeInterval(60))

        } else {

            print("Notification permission dendied !!")
        }
    }
}

func addNotification(content: UNMutableNotificationContent, date: Date) {

    let calendar = Calendar(identifier: .gregorian)

    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
    // Notification Request
    let routeNotificationRequest = UNNotificationRequest(identifier: "\(date.timeIntervalSince1970)", content: content, trigger: trigger)


    // Add request
    UNUserNotificationCenter.current().add(routeNotificationRequest) { (Error) in
        if Error != nil {
            print("something went wrong with adding notification")
        }
    }
}

可能是你的日期有问题!

在尝试了不同的方法后,我想我已经解决了它,但我不明白为什么它不能像我那样工作。 d 是从 setRouteNotification 函数中的 for in 循环中获取的日期值,表示要安排通知的工作日(请参阅问题中的代码) 工作:

let components2 = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: d)
let trigger2 = UNCalendarNotificationTrigger(dateMatching: components2, repeats: true)

不工作:

let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: d)
var newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, weekday: components.weekday)
let trigger = UNCalendarNotificationTrigger(dateMatching: NewComponents, repeats: true)

我遇到了同样的问题并意识到它正在发生,因为我对多个通知使用相同的标识符@"ID"。当我使标识符唯一时,它们都被触发了。

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ID" content:notification trigger:trigger];