简体   繁体   中英

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

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
}

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM