3

The code is for a podcasting app.

import AVKit

extension CMTime {
func toDisplayString() -> String {
    let totalSeconds = Int(CMTimeGetSeconds(self))
    let seconds = totalSeconds % 60
    let minutes = totalSeconds / 60
    let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
    return timeFormatString
}
}

It fails when selecting a podcast to play... resulting in audio playing but the app to freeze until rebooted.

Edit: The error ocurs on line let totalSeconds = Int(CMTimeGetSeconds(self))

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

2 Answers2

4

From the CMTimeGetSeconds documentation:

If the CMTime is invalid or indefinite, NaN is returned. If the CMTime is infinite, +/- infinity is returned.

When CMTimeGetSeconds returns NaN or infinity, casting the return value to an Int will throw the Fatal Error you are seeing.

You can first check the value then return some sort of default in case it's not a valid number.

func toDisplayString() -> String {
    let rawSeconds = CMTimeGetSeconds(self)
    guard !(rawSeconds.isNaN || rawSeconds.isInfinite) else {
       return "--" // or some other default string
    }
    let totalSeconds = Int(rawSeconds)
    let seconds = totalSeconds % 60
    let minutes = totalSeconds / 60
    let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
    return timeFormatString
}
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • Thank you... in another question I found this, but i was implementing it in the wrong place :) –  Nov 30 '18 at 16:40
1

The below code should work... basically it happens because the value that is returned by CMTimeGetSeconds(self) is beyond Int limit.

func toDisplayString() -> String {
        let totalSeconds:TimeInterval = TimeInterval(CMTimeGetSeconds(self))
        let seconds:TimeInterval = totalSeconds.truncatingRemainder(dividingBy: 60)
        let minutes:TimeInterval = totalSeconds / 60
        let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
        return timeFormatString
    }
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88