[英]Swift 3:fatal error: Double value cannot be converted to Int because it is either infinite or NaN
[英]Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
该代码适用于播客应用。
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))
如果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
}
下面的代码应该起作用...基本上会发生,因为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.