Kira Arik Kira Arik - 1 month ago 57
Swift Question

How to create Date from Components in Swift 3

I've stored day in a month and time. I am creating a notification and I need to do a little calculation and then create a date. I stuck at the part where I "glue" all parts into

Date
so I can create fireDate.

I'm not really sure how this works although I'm trying to figure it out using Apple documentation. As I gathered I need
DateComponents
but then I don't know how to proceed. There is only an
init()
method that takes so many parameters.

For now I have very little code:

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


Can somebody please clarify this for me?
Thanks a bunch.

Answer

It sounds like you want to create a notification to be fired at a specific date. You'll need to create a UNCalendarNotificationTrigger from DateComponents. So given a date, you would need to create a DateComponents object from that date.

// 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)

Here is the complete code you would need to fire a notification at a certain date:

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)
Comments