Mira
Mira

Reputation: 171

How do I convert Date into DateComponents in SwiftUI?

I want to set a daily notification at the time a user selects from a DatePicker, but I can't figure out how to convert the selected hour and minute into DateComponents to match the UNCalendarNotificationTrigger.

This is my DatePicker:

DatePicker("Choose time of notif", selection: $notifTime, displayedComponents: .hourAndMinute)

This is my notification trigger:

var dateComponents = DateComponents()
dateComponents = notifTime
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

Upvotes: 5

Views: 5041

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

You just need to get the dateComponents from the date property using the Calendar API, that needs to be repeated. So, in this case, the hour and minute repeats everyday so here's how you do this:

var notifTime: Date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: notifTime)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

Upvotes: 13

Related Questions