Reputation:
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))
Upvotes: 3
Views: 3405
Reputation: 29635
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
}
Upvotes: 4
Reputation: 13843
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
}
Upvotes: 2