How do I convert an NSTimeInterval
value to NSData
?
Asked
Active
Viewed 1,806 times
0
-
why do you need to do that? – Wain Nov 11 '15 at 14:57
-
to send to a peer the time i sent an invitation to him to see who sent it first (Multipeer connectivity), i have a problem that when 2 peers send invitations to one another before each of them recieved the invitation the other sent them, so both thinks they are the sender not the receiver. – Dror Chen Nov 11 '15 at 14:58
-
1so you're hoping both devices times are set correctly so you can compare? send an NSDate that you can easily archive – Wain Nov 11 '15 at 15:02
-
so how do i convert NSDate to NSData? – Dror Chen Nov 11 '15 at 15:05
-
Posted an answer tested with Xcode 7 and Swift 2.0. Let me know if you're using a different version of Swift and this doesn't work. – JAL Nov 11 '15 at 15:15
3 Answers
4
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"

Leo Dabus
- 229,809
- 59
- 489
- 571
3
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

JAL
- 41,701
- 23
- 172
- 300
-
This does not work with XCode 7.2, etc ... won't accept the "&" and then, after removing, throws an error about casting to an UnsafePointer. – Dan Dec 19 '15 at 19:56
-
@DanShev working fine for me in a Swift iOS Playground in Xcode 7.2 http://i.stack.imgur.com/dNhdk.png. Can you post the full context where you're calling this code? – JAL Dec 20 '15 at 15:36
3
You may also use NSKeyedArchiver
:
let time = NSTimeInterval(100)
let archivedTime = NSKeyedArchiver.archivedDataWithRootObject(time)
let unarchivedTime = NSKeyedUnarchiver.unarchiveObjectWithData(archivedTime) as! NSTimeInterval

Tomas Camin
- 9,996
- 2
- 43
- 62
-
This isn't the best solution, as `unarchiveObjectWithData` can raise an exception. But because this method doesn't "throw" its exception, there is no way to catch it with Swift, which can cause your app to crash. – JAL Nov 15 '15 at 17:06