What’s the optimum way of storing an NSDate in NSUserDefaults?

You are needlessly complicating things. Why are you converting the date to a time interval (then the time interval to a different primitive)? Just [sharedDefaults setObject:theDate forKey:@”theDateKey”] and be done with it. NSDate is one of the “main types” supported by the PLIST format (dates, numbers, strings, data, dictionaries, and arrays), so you can just … Read more

How to convert an NSTimeInterval (seconds) into minutes

Brief Description The answer from Brian Ramsay is more convenient if you only want to convert to minutes. If you want Cocoa API do it for you and convert your NSTimeInterval not only to minutes but also to days, months, week, etc,… I think this is a more generic approach Use NSCalendar method: (NSDateComponents *)components:(NSUInteger)unitFlags … Read more

Convert a Date (absolute time) to be sent/received across the network as Data in Swift?

You can send your Date converting it to Data (8-bytes floating point) and back to Date as follow: extension Numeric { var data: Data { var source = self return .init(bytes: &source, count: MemoryLayout<Self>.size) } init<D: DataProtocol>(_ data: D) { var value: Self = .zero let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} ) assert(size … Read more

How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

Brief Description Just another approach to complete the answer of JBRWilkinson but adding some code. It can also offers a solution to Alex Reynolds’s comment. Use NSCalendar method: (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts “Returns, as an NSDateComponents object using specified components, the difference between two supplied dates”. (From the API documentation). Create 2 … Read more

How can I use Timer (formerly NSTimer) in Swift?

This will work: override func viewDidLoad() { super.viewDidLoad() // Swift block syntax (iOS 10+) let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print(“Done!”) } // Swift >=3 selector syntax let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) // Swift 2.2 selector syntax let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, … Read more

tech