【问题标题】:Scheduling local notifications to repeat daily from tomorrow安排本地通知从明天开始每天重复
【发布时间】:2021-12-29 00:14:59
【问题描述】:

我正在尝试安排本地通知在每天的特定时间触发,但从明天开始。

例如"从明天开始,每天下午 2 点触发通知"

这就是我设置日程功能的方式。

func scheduleNotifications(date: Date, identfier: String, after: Bool) {
    
    let content = UNMutableNotificationContent()
    content.title = "App"
    content.body = "Test."
    content.sound = .default
    content.userInfo = ["Hour": Int(hourFormatter.string(from: date)) ?? 0]
    
    let afterDay = Calendar.current.date(byAdding: .day, value: after ? 1 : 0, to: Date())

    var components = Calendar.current.dateComponents([.hour, .minute], from: afterDay!)

    components.hour = Int(hourFormatter.string(from: date)) ?? 0
    components.minute = Int(minuteFormatter.string(from: date)) ?? 0
    
    
    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request)

}

【问题讨论】:

  • 请不要删除您的original question 以便下次创建新的,而是对其进行编辑以解决导致否决/关闭投票的问题。通常在此之后,downvotes 将被退回。更多信息可以找到here

标签: swift notifications usernotifications


【解决方案1】:

此代码用于每日通知,只需在明天的计划时间调用它

func setupNotificationSettings() {

DispatchQueue.main.async {
    let content: UNMutableNotificationContent = UNMutableNotificationContent()
    
    content.title = AppName
    content.body = "APP_Body"
    content.sound = UNNotificationSound.default
    
    let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
    let request: UNNotificationRequest = UNNotificationRequest(identifier: "\(AppName)_Local", content: content, trigger: trigger)
    
    let center: UNUserNotificationCenter = UNUserNotificationCenter.current()
    center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
    center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
    center.add(request) { (error) in
        
    }
}
}

【讨论】:

  • 但我也希望它在特定时间重复,所以最好使用 UNCalendarNotificationTrigger
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
相关资源
最近更新 更多