计划的IOS本地通知每分钟重复一次

计划的IOS本地通知每分钟重复一次,ios,swift4,uilocalnotification,Ios,Swift4,Uilocalnotification,我有一个IOS应用程序,它在应用程序打开的当天安排一个本地通知,并且在接下来的7天中每天都在大致相同的时间。每次通知都会重复我计划的天数,因此在这种情况下,每次通知都会重复8次,每天每分钟一次,而不是每天重复一次,持续8天。我认为这可能是由于标识符,但我已尝试使其尽可能唯一,以下是我的代码: 其中scheduleDate是我循环使用的日期数组: func getNextNDays(numberOfDays: Int) -> [Date] { let today = Date()

我有一个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]

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

您已经展示了如何安排一个通知,但是您可以展示您安排一系列通知的代码吗?您好,Paul,我已经更新了问题。您正在计划在每次运行此代码时使用唯一标识符发送新通知。由于标识符是唯一的,因此新通知将与以前计划的通知一起计划。您应该在计划新通知之前取消所有现有通知。我可以通过调用:unuserviceNotificationCenter.current()。removeAllPendingNotificationRequests()-但是这不能解释为什么我会收到7次相同的通知(在计划时间内每分钟一次)而不是一天一次持续7天?你的触发组件只有小时、分钟和秒。您需要包括日期和时间,否则所有7个通知触发器今天都匹配。
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)")
        }
    }
}