预定的 IOS 本地通知每分钟重复一次

时间:2021-04-15 16:09:15

标签: ios swift4 uilocalnotification

我有一个 IOS 应用程序,它在应用程序打开的那一天安排本地通知,并且在接下来的 7 天内每天大约在同一时间。发生的情况是每个通知重复我安排的天数,因此在这种情况下,每个通知重复 8 次,每天每分钟一次,而不是每天一次,持续 8 天。我认为这可能是由于标识符的原因,但我已尝试使其尽可能独特,这是我的代码:

其中 scheduleDate 是我循环的日期数组:

func getNextNDays(numberOfDays: Int) -> [Date] {
    let today = Date()
    var days = [Date]()
        
    for i in 1...numberOfDays {
        let nextNDay = Calendar.current.date(byAdding: .day, value: i, to: today) ?? Date()
        days.append(nextNDay)
    }
        
    return days
}

let numberOfDaysForNotifications = 7
let nextNDays = getNextNDays(numberOfDays: numberOfDaysForNotifications)

for nextDate in nextNDays {
    scheduleNotification(scheduleDate: nextDate)
}

// nextNDays contains
[2021-04-15 17:03:54 +0000, 2021-04-16 17:03:54 +0000, 2021-04-17 17:03:54 +0000, 2021-04-18 17:03:54 +0000, 2021-04-19 17:03:54 +0000, 2021-04-20 17:03:54 +0000, 2021-04-21 17:03:54 +0000]
func scheduleNotification(scheduleDate: Date) {
    let date = scheduleDate
    let triggerDate = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "Some title"
    content.body = "Some body"
    content.badge = 0
    content.sound = UNNotificationSound.default

    let formatter = DateFormatter()
    formatter.dateFormat = "HHmmEdMMMy"

    let identifier = notificationTitle + formatter.string(from: scheduleDate) + UUID().uuidString
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    notificationCenter.add(request) { (error) in
        if let error = error {
            print("Error scheduling notification \(error.localizedDescription)")
        }
    }
}

知道这里可能有什么问题吗?

0 个答案:

没有答案