Ios 每隔x分钟在“之间”重复一些操作;A「;a、 m.“和”;B";下午

Ios 每隔x分钟在“之间”重复一些操作;A「;a、 m.“和”;B";下午,ios,swift,notifications,nstimer,Ios,Swift,Notifications,Nstimer,如何运行例如本地通知? 在UnuseNotificationCenter中没有重复功能。 也许是使用NSTimer或类似的东西 为什么我的代码不能像我期望的那样工作 let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] for hour in hours { for minute in stride(from: 0, to: 60, by: 5){

如何运行例如本地通知? 在UnuseNotificationCenter中没有重复功能。 也许是使用NSTimer或类似的东西

为什么我的代码不能像我期望的那样工作

let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    for hour in hours {
        for minute in stride(from: 0, to: 60, by: 5){
            let content = UNMutableNotificationContent()
            content.title = "Title"
            content.body = "Body"

            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request) { (error : Error?) in
                if let theError = error {
                    print(theError.localizedDescription)
                }
            }

        }
    }

有一个重复功能

发件人:


编辑:

正如文档中所述,您当然必须拥有发布通知的用户权限:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization
}
结果:

通知每分钟发布一次:


您可以使用
直到IntervalNotificationTrigger
取消通知中心
中安排重复通知,但您不能指定它将在一天中的某个时间停止重复,并在另一个时间重新开始。可能也是一个选项。为什么此代码不每5分钟创建一次通知?我考虑了更新的答案,但如果我想在for-in循环中使用UNCalendarNotificationTrigger,它不会创建通知@Paulw11“它不起作用”不是一个很有用的描述。我确实试过了,在这里工作如预期。请参阅更新的答案。您是对的。它没有像我预期的那样工作。非常感谢。如果我需要使用UNCalendarNotificationTrigger怎么办?这与问题无关。为UNCalendarNotificationTrigger写一个新问题,说明您尝试了什么,并描述您的方法中出现的问题。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization
}