TheDoge TheDoge - 7 months ago 20
Swift Question

How to save time interval in NSUserDefaults

I am trying to save

NSDate.timeIntervalSinceReferenceDate()
in
NSUserDefaults
by doing this in a playground-

var date2 = Double(NSDate.timeIntervalSinceReferenceDate())
NSUserDefaults.standardUserDefaults().setDouble(date2, forKey: "timeInterval")
NSUserDefaults.standardUserDefaults().synchronize()


And I am trying to retrieve this date by doing this-

NSUserDefaults.standardUserDefaults().doubleForKey("timeInterval")


But when I print this, I get the output as 0. How can I change that to get the correct time interval as a double? Thanks in advance.

Answer

Try to save it as object for key maybe,

NSUserDefaults.standardUserDefaults().setObject(date2, forKey:"yourKey")
NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as! NSDate 

Edit:

You can't access to NSUsersDefaults in the Playground environnement, You can see why here