I'd like to pass an NSDateComponents
object to my UILocalNotification
object's userInfo
property. What is the most elegant way of doing this?
I'm working with EKReminders
and am passing their dueDateComponents
(which are of type NSDateComponents
.) I'm also passing two Strings, so I'm thinking maybe I'll just pass the NSDateComponent
's description
property. (I can't pass the NSDateComponent
itself because it's not a valid 'property list type') When I receive the local notification I need to make an NSDateComponents
again back out of the String. I'm doing that with the following code, but I'm not sure it'll always work (for every locale?) because I don't know whether the dueDateComponents always has the same format as below...
Is this really the best/most stabile way of passing NSDateComponents?
let duedatestrTime = "2016-10-01 01:00:00 +0000"
// MARK: date utilities
extension String {
func toDate() -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" // IS THIS RELIABLE? DO I KNOW THAT EKReminders.dueDateComponents ALWAYS HAVE THIS FORMAT? IF NOT IT'LL RETURN NIL...
return dateFormatter.dateFromString(self)
}
}
extension NSDate {
func toNSDateComponents() -> NSDateComponents {
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year, .Hour, .Minute]
return NSCalendar.currentCalendar().components(unitFlags, fromDate: self)
}
}
let x = strTime.toDate().toNSDateComponents()
NSDate is a valid type to use. Why not just convert the components to an NSDate to pass it in, and then convert it back to components on the way out if that's what you need?