I have a UIDatePicker
which is restricted to time only. The app saves the selected time from the datePicker in a variable and when this time is reached it fires a UILocalNotification
.
So there is a label which shows the remaining time until the Local Notification fires. So it basically works a bit like a countdown Timer. How can I achieve this?
Date to String: (for displaying the fireDate)
func formatTimeForDisplay(date:NSDate) -> String {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.timeStyle = NSDateFormatterStyle.ShortStyle
return formatter.stringFromDate(date)
}
Extension for NSLocalNotification: (for converting the NSDate from UIDatePicker to fireDate for the LocalNotification)
extension NSDate {
var minute: Int {
return NSCalendar.currentCalendar().component(.Minute, fromDate: self)
}
var hour: Int {
return NSCalendar.currentCalendar().component(.Hour, fromDate: self)
}
var day: Int {
return NSCalendar.currentCalendar().component(.Day, fromDate: self)
}
var month: Int {
return NSCalendar.currentCalendar().component(.Month, fromDate: self)
}
var year: Int {
return NSCalendar.currentCalendar().component(.Year, fromDate: self)
}
var fireDate: NSDate {
let today = NSDate()
return NSCalendar.currentCalendar().dateWithEra(1,
year: today.year,
month: today.month,
day: { hour > today.hour || (hour == today.hour
&& minute > today.minute) ? today.day : today.day+1 }(),
hour: hour,
minute: minute,
second: 0,
nanosecond: 0
)!
}