【问题标题】:Repeat UNNotifications every day and every half hour每天和每半小时重复一次 UNNotifications
【发布时间】:2017-07-15 09:49:41
【问题描述】:

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

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。任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: ios swift


    【解决方案1】:

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

    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 变量中传递 start Date,在 dateEnd 变量中传递 Date End Date。

    【讨论】:

    • 开始日期是一天中的开始时间,结束日期是一天中的结束时间吗?意思是如果我将早上 7 点作为开始日期,将晚上 7 点作为结束日期,那么通知是否会在这些时间之间每半小时每天出现一次?
    • @Waqar Khalid 是的,如果您将 dateStart 设置为早上 7 点,将 dateEnd 设置为晚上 7 点,那么在这些时间之间的每一天,每隔半小时就会显示一次通知。
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多