如何将CMTime存储在UserDefaults中,然后进行解析?

时间:2019-01-05 22:58:05

标签: swift nsuserdefaults cmtime

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

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

1 个答案:

答案 0 :(得分:0)

这是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")
    }
}