gpt4 book ai didi

ios - 如何在 Swift 3 中从组件创建日期

转载 作者:搜寻专家 更新时间:2023-11-01 07:19:07 25 4
gpt4 key购买 nike

我已经存储了一个月中的一天和时间。我正在创建一个通知,我需要做一些计算然后创建一个日期。我停留在将所有部分“粘合”到 Date 中的部分,这样我就可以创建 fireDate。

我不太确定它是如何工作的,尽管我正在尝试使用 Apple 文档弄清楚它。据我所知,我需要 DateComponents 但我不知道如何继续。只有一个 init() 方法接受了这么多参数。

目前我只有很少的代码:

let calendar = Calendar(identifier: .gregorian)
let components = DateComponents()
calendar.date(from: components)

有人可以为我澄清一下吗?非常感谢。

最佳答案

听起来您想创建一个在特定日期触发的通知。您需要从 DateComponents 创建一个 UNCalendarNotificationTrigger。因此,给定一个日期,您需要从该日期创建一个 DateComponents 对象。

// Assuming your UIDatePicker is named `datePicker`
let triggerDate = datePicker.date
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: triggerDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

这是在特定日期触发通知所需的完整代码:

let content = UNMutableNotificationContent()
content.title = "Notification Title"
let triggerDate = datePicker.date
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: triggerDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: nil, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

关于ios - 如何在 Swift 3 中从组件创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com