[英]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))
编辑:错误发生在线上let totalSeconds = Int(CMTimeGetSeconds(self))
From the CMTimeGetSeconds
documentation : 从CMTimeGetSeconds
文档 :
If the CMTime is invalid or indefinite, NaN is returned. 如果CMTime无效或不确定,则返回NaN。 If the CMTime is infinite, +/- infinity is returned. 如果CMTime是无限的,则返回+/-无限。
When CMTimeGetSeconds
returns NaN or infinity, casting the return value to an Int
will throw the Fatal Error you are seeing. 当CMTimeGetSeconds
返回NaN或无穷大时,将返回值强制转换为Int
会抛出致命错误。
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. 下面的代码应该起作用...基本上会发生,因为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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.