Reputation: 51
How do I convert an NSTimeInterval
value to NSData
?
Upvotes: 0
Views: 1857
Reputation: 236508
Xcode 8.3.1 • Swift 3.1
var nowInterval = Date().timeIntervalSince1970 // 1491800604.362141
let data = Data(bytes: &nowInterval, count: MemoryLayout<TimeInterval>.size) // 8 bytes
let timeInterval: Double = data.withUnsafeBytes{ $0.pointee }
let date = Date(timeIntervalSince1970: timeInterval) // Apr 10, 2017, 2:03 AM"
Upvotes: 4
Reputation: 10096
You may also use NSKeyedArchiver
:
let time = NSTimeInterval(100)
let archivedTime = NSKeyedArchiver.archivedDataWithRootObject(time)
let unarchivedTime = NSKeyedUnarchiver.unarchiveObjectWithData(archivedTime) as! NSTimeInterval
Upvotes: 3
Reputation: 42489
NSTimeInterval
is just a typealias of Double
. You can archive it by copying the bytes like you would with any other Foundation type.
var time = NSTimeInterval(100) // 100.0
let timeData = NSData(bytes: &time, length: sizeof(NSTimeInterval))
var unarchivedTime = NSTimeInterval() // You need to initialize an empty NSTimeInterval object as a var in order to mutate it
timeData.getBytes(&unarchivedTime, length: sizeof(NSTimeInterval))
print(unarchivedTime) // 100.0
Upvotes: 3