开发者社区 问答 正文

关于SWIFT中日程通知工作日设置的问题

我昨天发了这篇文章。

关于SWIFT中待批准的计划通知的问题

幸运的是,昨天的帖子解决了这个问题。(重复触发器的问题)

但我还是把闹钟设在星期一,下午6点40分,然后推到周一,但不是在星期一,韦德。

我试图用另一种方式解决这个问题。

代码:

func scheduleNotification() {
​
   let center = UNUserNotificationCenter.current()
​   let hour = 6
​   let minute = 40
​   let weekdays = [2,3,4] // mon, tue, wed
​   let content = UNMutableNotificationContent()
​
   content.title = "Fire!!"
   content.body = "test.!"
   content.badge = 1
   content.categoryIdentifier = "alarm"
   content.userInfo = ["customData": "fizzbuzz"]
   content.sound = UNNotificationSound.default
​
   for weekday in weekdays {
       var dateComponents = DateComponents()
       dateComponents.hour = hour
       dateComponents.minute = minute
       dateComponents.weekday = weekday

       let date = Calendar.current.date(from: dateComponents)
       let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute], from: date!)
       let trigger = UNCalendarNotificationTrigger.init(dateMatching: triggerWeekly, repeats: true)

       let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

       center.add(request) { (error) in
                if error != nil {
                    print("error.localizedDescription : ",error?.localizedDescription)
                }
            }
      }
   center.getPendingNotificationRequests { (requests) in
            for request in requests {
                print("trigger: \(request.trigger)")
            }
        }
}

我想用上面的代码重复一天。但当我把预定的触发器打印到控制台时,

trigger : Optional(<UNCalendarNotificationTrigger: 0x283242f20; dateComponents: <NSDateComponents: 0x2830567a0> {
    Hour: 6
    Minute: 40
    Weekday: 7, repeats: YES>)
trigger : Optional(<UNCalendarNotificationTrigger: 0x283241920; dateComponents: <NSDateComponents: 0x283056900> {
    Hour: 6
    Minute: 40
    Weekday: 7, repeats: YES>)
trigger : Optional(<UNCalendarNotificationTrigger: 0x2832416a0; dateComponents: <NSDateComponents: 0x2830556f0> {
    Hour: 6
    Minute: 40
    Weekday: 7, repeats: YES>)

上面的日志被拿走了。我想要的日志是平日应该是2,3,4,但我不知道为什么7是3倍。帮帮我。

展开
收起
游客5akardh5cojhg 2019-12-24 13:11:14 1272 分享 版权
阿里云 AI 助理回答

从你的代码和描述来看,你希望在每周的星期一(2)、星期二(3)和星期三(4)的特定时间(6:40 PM)设置重复提醒。但是,日志显示触发器被设置为星期日(7),并且重复了三次,这显然与你的预期不符。

问题出在你如何构建DateComponents对象并将其转换为日期上。特别地,你直接使用数组中的weekday值来设置dateComponents.weekday,而Swift的周日是从1开始的,所以当你写weekdays = [2,3,4]时,实际上代表的是周二、周三、周四,而不是你期望的周一至周三。但错误在于打印出来的日志显示的是周日(7),这表明问题可能在于日期处理或打印逻辑中。

为了修正这个问题,请确保你在创建DateComponents时正确地映射了weekday值,并且检查你的环境或系统是否有可能影响到weekday值的其他因素。这里是一个修改后的代码示例,明确了weekday的设定,并简化了部分逻辑以提高可读性和准确性:

func scheduleNotification() {
    let center = UNUserNotificationCenter.current()
    let hour = 6
    let minute = 40
    let weekdays = [2, 3, 4] // Ensure these are correct for your needs (Mon=2, Tue=3, Wed=4 in Swift)

    let content = UNMutableNotificationContent()
    content.title = "Fire!!"
    content.body = "test.!"
    content.badge = 1
    content.sound = UNNotificationSound.default

    weekdays.forEach { weekday in
        var dateComponents = DateComponents()
        dateComponents.hour = hour
        dateComponents.minute = minute
        // In Swift, Sunday is 1 and Saturday is 7, so ensure weekdays are correctly mapped.
        // No change needed here since your array already represents Mon to Wed correctly as per Swift's standard.
        dateComponents.weekday = weekday

        // Safely attempt to get a valid date from components, considering the weekday might not be applicable on the current calendar setup.
        if let date = Calendar.current.nextDate(after: Date(), matching: dateComponents, matchingPolicy: .nextTime, direction: .forward, limit: 1) {
            let trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.weekday, .hour, .minute], from: date), repeats: true)
            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
            
            center.add(request) { error in
                if let error = error {
                    print("Error adding notification: \(error.localizedDescription)")
                }
            }
        } else {
            print("Unable to find a valid date for weekday: \(weekday)")
        }
    }

    // Fetching pending notifications is good for debugging but not necessary for scheduling.
}

这段代码通过Calendar.current.nextDate(after:matching:matchingPolicy:direction:limit:)方法确保找到下一个符合指定weekday、hour、minute的时间点,这样可以更准确地设置触发器。同时,它也提供了更好的错误处理和日志信息,帮助你调试为何之前会出现不正确的weekday值。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答标签:
问答地址: