在Swift中安排本地通知从明天开始每天重复

14

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

例如:“从明天起,每天下午8点触发一次通知”

我参考了这个 Stack Overflow 网站上的问题作为指导,并且我认为我正在按照它所说的做,但是如果我在今天之前安排通知(例如在下午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))")
        }
    }

}

我相信当我在代码中仅设置components.hour和components.minute时,这就是我正在做的事情?虽然nextTriggerDate函数很有用,因为它意味着我可以进行测试而不必不断更改我的系统日期! - Dominic Williams
不要忘记添加唯一标识符。 - Leo Dabus
你想让你的通知每天重复,但是你想跳过第一次出现。我认为这是不可能的。有一个类似的问题 https://stackoverflow.com/q/41449749/2303865 - Leo Dabus
那似乎是这样的!无论如何,感谢您的帮助。 - Dominic Williams
1
请查看此答案 - Brooketa
显示剩余6条评论
1个回答

0

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 = "标题"
     content.body = "正文"
     let request = UNNotificationRequest(identifier: "标识符", content: content, trigger: trigger)
     UNUserNotificationCenter.current().add(request) { 
         if let error = $0 {
             print(error)
             return
         }else { 
             print("已安排") 
         }
     }
    

我已经尝试了上述代码,但它并没有按照我们需要的方式工作,因为我们需要从明天开始安排通知。每次 "dateComponent" 都保持不变。我们需要更改组件的值以针对特定日期或 +1 天进行调整,如果我们使用上述代码,则它将在特定日期而不是日期和时间重复。 - Azharhussain Shaikh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接