ios - 每天和每半小时重复一次 UNNotifications

标签 ios swift

我想在用户选定的时间之间向用户显示本地通知,并每半小时重复一次该通知,直到选定的时间限制到来,并且每天重复一次该通知。 我用过这段代码

let components = calendar.dateComponents(in: .current, from: date)
     var triggerDate = DateComponents()
            triggerDate.hour = components.hour
            triggerDate.minute = components.minute
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

但这只会在用户选择的特定时间每天重复通知,但我也想从那个特定时间开始每半小时重复一次。我使用了 UNNotifications。任何帮助将不胜感激。谢谢

最佳答案

如果您想在所选时间之间每半小时显示一次本地通知,则必须使用不同的通知标识符为每个小时设置不同的通知:

var dateStart = "Pass Your Start Date for Notification."
let dateEnd = "Pass Your End Date for Notification."

//Check Start Date is less then End Date is not.        
while dateStart < dateEnd {

     dateStart = dateStart.addingTimeInterval(0.5 * 60 * 60) //Add half an hour to start time

    //Schedule notification With body and title.
    scheduleNotification(at: dateStart, body: "Show Me", titles: "Remainder")

}

通过以下函数实现通知:

//Schedule Notification with Daily bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

    let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: date)

    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

    let content = UNMutableNotificationContent()
    content.title = titles
    content.body = body
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "todoList"

    let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
  //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("Uh oh! We had an error: \(error)")
        }
    }
}

在 dateStart 变量中传递开始 Date,在 dateEnd 变量中传递 Date 结束日期。

关于ios - 每天和每半小时重复一次 UNNotifications,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116819/

相关文章:

ios - 将 SKShapeNode 放置在彼此之上以获得图形效果

ios - 社交网络应用程序如何实时更新其 UI?

iOS - 当用户在设置中手动打开推送通知时的委托(delegate)方法

ios - Swift - 如何将触摸事件传递到属于第二个 UIWindow 的多个按钮,但忽略其他所有内容

objective-c - 无法呈现 IB Designables 的实例

ios - 如何添加指向 map 上图钉的 GPS?

ios - 无法识别的选择器发送到实例 NSArrayM

ios - 带有对象映射器的动态键

ios - 在 C 中抛出 Swift 可以捕获的事件

swift - 如何在 Swift 的 tableView 中仅显示从字典中获取的某些单元格