swiftnancmtime

Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN


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))


Solution

  • 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
    }