-1

I am getting a lot of reports that a function that is called by applicationWillTerminate, not exclusively by that but I have a feeling that the root of the issue might have something to do with that. I am getting these reports from Fabric.io Crashlytics. Anyways the reported line causing the crash is the following:

return Int(NSDate().timeIntervalSince1970 * 1000)

This code has also been working in most cases but has risen up the list of crashes. Can anyone give me any hint as to why this might be crashing.

Alex Harris
  • 6,172
  • 2
  • 32
  • 57

1 Answers1

3

My guess is that your crashes are coming from 32-bit devices, where Int(NSDate().timeIntervalSince1970 * 1000) is impossible because NSDate().timeIntervalSince1970 * 1000 is bigger than Int.max.

Here's a little playground code to show that that is true:

let i = Int32.max // max size of Int on 32-bit
i // 2147483647
let j = NSDate().timeIntervalSince1970 * 1000
j // 1486250171084.633

And we can proceed to test it like this:

// let's try to simulate the crash
Int32(j)
// yup, crash: 
// "Double value cannot be converted to Int32 because the result would be greater than Int32.max"
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Just a guess. But it does cover (a) the line in question and (b) the "sometimes" part! :) – matt Feb 04 '17 at 23:52
  • All the crashes are from iPhones 5 and below so it makes perfect sense. – Alex Harris Feb 05 '17 at 02:30
  • Excellent, thanks for the confirmation. – matt Feb 05 '17 at 02:30
  • @chasenyc According to the release notes from Swift 3.1 beta there will be a new family of `exactly` initializers that will be failable. Thus, if I understand correctly, you'll be able to say `let k = Int32(exactly:j)` and `k` will be `nil` if we couldn't do that. This will allow you to avoid crashing in this situation. – matt Feb 11 '17 at 03:53