【问题标题】:Reading out the day of the week via Date () for local notifications in SwiftUI在 SwiftUI 中通过 Date() 读取星期几以获取本地通知
【发布时间】:2021-02-05 17:36:53
【问题描述】:

我正在尝试发送带有本地通知的特定消息,这取决于星期几,现在我的代码必须知道它是星期几才能发送通知。

谢谢。

【问题讨论】:

    标签: swift swiftui uilocalnotification


    【解决方案1】:

    您可以像这样获取当前日期的单个组件(在我们的例子中是星期几):

    if Calendar.current.component(.weekday, from: Date()) == 1 {
        // Yay, it's Sunday!
    }
    

    来自文档:“工作日单位是数字 1 到 N(公历 N=7,1 是星期日)。”

    【讨论】:

    • 好的,但我也可以使用 UNTimeIntervalNotificationTrigger 触发器触发通知。或类似的东西?
    • 你最初的问题不是很清楚,但是UNTimeIntervalNotificationTrigger需要一个时间间隔。我假设您想在即将到来的工作日触发通知。 CalendarDateComponents 帮助您计算该间隔。
    • 这样的事情会触发下周日上午 10 点:let nextDate = Calendar.autoupdatingCurrent.nextDate(after: Date(), matching: DateComponents(hour: 10, weekday: 1), matchingPolicy: .nextTime); let interval = nextDate?.timeIntervalSinceNow; let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false)
    • 是的,这就是我想要的。
    【解决方案2】:

    看起来你想要这个(或其他日期)

    if let weekDay = Calendar.current.dateComponents([.weekday], from: Date()).weekday {
       // do this what's needed
    }
    

    【讨论】:

    • 最后一部分应该是 .weekday 而不是 .day?
    • @Subha_26,你是对的。这将返回 nil,因为只请求了 .weekday 组件,但返回了 .date 组件。
    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多