如何取消特定的重复本地通知并在 iOS 10(Swift) 中将其重新安排到下周

How to cancel particular recurring local notification and reschedule it for next week in iOS 10(Swift)

我创建了不同的本地通知来设置工作日和周末连续重复

let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.body = "TIME_TO_STEP_SHAPA".localized
content.sound = UNNotificationSound.default()

let request = UNNotificationRequest(identifier: "\(notificationType)-\(reminderType)-\(day)", content: content, trigger: trigger)

UNUserNotificationCenter.current().getNotificationSettings { (settings) in
    if settings.authorizationStatus != .authorized {
        print("Local notifications are not authorized by the user")
    }
}
UNUserNotificationCenter.current().add(request) {(error) in
    if error != nil {
        print("Error: \(error?.localizedDescription)")
    }
}

并取消特定通知,根据适当的条件验证通知,并为下周更新相同的通知。

if (type == notificationType && notificationWeekDay == currentWeekDay) {
    //Cancelling local notification
    app.cancelLocalNotification(notif)

    let fireDate = self.getUpdatedNotification(currentDate: currentLocalDate!, fireDate: notificationFireDate!)

    HikeCommonUtils.setUpLocalNotification(fireDate, type: notificationType, reminderType: reminderType)
}

并使用

更新下一个开火日期
func getUpdatedNotification(currentDate: Date, fireDate : Date) ->Date {
    let calendar = Calendar.autoupdatingCurrent
    let dateComponents = (calendar as NSCalendar).components(([.year, .month, .day]), from: currentDate)
    let timeComponents = (calendar as NSCalendar).components(([.hour, .minute, .second]), from: fireDate)
    var dateComps = DateComponents()
    dateComps.day = dateComponents.day! + 7
    dateComps.month = dateComponents.month
    dateComps.year = dateComponents.year
    dateComps.hour = timeComponents.hour
    dateComps.minute = timeComponents.minute
    dateComps.second = timeComponents.second
    let itemDate = calendar.date(from: dateComps)
    return itemDate!
}

即使在删除通知后由于重复 'true' 而触发已删除的日期。

在 iOS 10 的本地通知中是否有添加开始日期的选项?

提前致谢!!

您可以将逻辑添加到 nextTriggerDate()

func nextTriggerDate()

下次满足触发条件的日期。

讨论

使用此 属性 可查明下一次发送与此触发器关联的通知的时间。

更新通知触发器详细信息

var triggerWeekly = calendar.dateComponents([.hour, .minute, .second], from: fireDate)
        triggerWeekly.weekday = day

而不是

            let triggerWeekly = calendar.dateComponents([.weekday, .hour, .minute, .second], from: fireDate)

为 firedate 更新工作