簡體   English   中英

接收致命錯誤:雙精度值不能轉換為Int,因為它是無窮大或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))

CMTimeGetSeconds文檔

如果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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM