如何将 CMTime 存储在 UserDefaults 中然后解析它?

How can I store CMTime in UserDefaults and then parse it?

好吧,我尝试在设备内存中记住AVPlayer 的currentTime(),以便在应用重启后继续播放视频。

我正在开发用于观看 Raspberry PI 电影的应用程序。有什么想法吗?

这是 UserDefaults 的扩展,可让您保存和恢复 CMTime 值:

import CoreMedia

extension UserDefaults {
    func cmtime(forKey key: String) -> CMTime? {
        if let timescale = object(forKey: key + ".timescale") as? NSNumber {
            let seconds = double(forKey: key + ".seconds")
            return CMTime(seconds: seconds, preferredTimescale: timescale.int32Value)
        } else {
            return nil
        }
    }

    func set(_ cmtime: CMTime, forKey key: String) {
        let seconds = cmtime.seconds
        let timescale = cmtime.timescale

        set(seconds, forKey: key + ".seconds")
        set(NSNumber(value: timescale), forKey: key + ".timescale")
    }
}