【问题标题】:Scheduling local notifications to repeat daily from tomorrow in Swift从明天开始在 Swift 中安排本地通知每天重复
【发布时间】:2017-12-05 22:43:16
【问题描述】:

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

即“从明天开始,每天晚上 8 点触发通知”

我一直使用this SO 问题作为指导,我相信我正在做它所说的但我今天运行以下代码时仍然收到通知(例如,如果我在晚上 8 点之前安排通知) :

    func testDateNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Test"
    content.body = "This is a test"
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())

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

    components.hour = 20
    components.minute = 00


    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if ((error) != nil){
            print("Error \(String(describing: error))")
        }
    }

}

【问题讨论】:

  • stackoverflow.com/a/42892780/2303865 你可以使用这个每周作为起点,你只需要删除工作日日期组件以每天重复它
  • 当我只在代码中设置 components.hour 和 components.minute 时,我相信这就是我正在做的事情?尽管 nextTriggerDate 函数很有用,因为它意味着我可以在不不断更改系统日期的情况下进行测试!
  • 别忘了添加唯一标识符。
  • 我的代码中有“test”作为标识符?还是我错过了什么?如果你看一下这个快速操场,下一个触发日期将永远是今天结束,而不是明天结束:pastebin.com/b6rDvczZ
  • 看看这个answer

标签: ios swift uilocalnotification unnotificationtrigger


【解决方案1】:

import UserNotifications

  1. 检查用户权限

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
    if $0 { } }
    
  2. 添加通知

     let fromDate = Date(timeIntervalSince1970: Double(0.0))
    
     let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
    
     let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
     print(trigger.nextTriggerDate() ?? "nil")
    
     let content = UNMutableNotificationContent()
     content.title = "title"
     content.body = "body"
     let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
     UNUserNotificationCenter.current().add(request) { 
         if let error = $0 {
             print(error)
             return
         }else { 
             print("scheduled") 
         }
     }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多