【问题标题】:Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN收到致命错误:双精度值无法转换为 Int,因为它是无限的或 NaN
【发布时间】:2018-11-30 05:03:34
【问题描述】:

代码用于播客应用。

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

选择要播放的播客时失败...导致音频播放,但应用程序冻结,直到重新启动。

编辑:错误发生在let totalSeconds = Int(CMTimeGetSeconds(self))

【问题讨论】:

    标签: swift nan cmtime


    【解决方案1】:

    来自CMTimeGetSeconds documentation

    如果 CMTime 无效或不确定,则返回 NaN。如果 CMTime 是无限的,则返回 +/- 无穷大。

    CMTimeGetSeconds 返回 NaN 或无穷大时,将返回值转换为 Int 将引发您看到的致命错误。

    您可以先检查该值,然后返回某种默认值,以防它不是有效数字。

    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
    }
    

    【讨论】:

    • 谢谢...在另一个问题中我找到了这个,但我在错误的地方实现它:)
    【解决方案2】:

    下面的代码应该可以工作......基本上它发生是因为CMTimeGetSeconds(self)返回的值超出了Int的限制。

    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
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      相关资源
      最近更新 更多