swiftnsuserdefaultscmtime

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


Well, I try to remember currentTime() from AVPlayer in the device memory, for continue playing video after app restart.

I'm making app for watching films from my Raspberry PI. Any ideas?


Solution

  • Here's an extension to UserDefaults that lets you save and restore a CMTime value:

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