-2

Is there anyway that i can save an NSTimer to UserDefaults and NSKeyedUnarchiver and use it later ? Below is my example code

  static var timerDictionary : [String:Timer]? {
    get{
        let outData = UserDefaults.standard.data(forKey: "timerDictionary") ?? Data()
        if let dict = NSKeyedUnarchiver.unarchiveObject(with: outData) as? [String:Timer]?{
            
            return dict
        }else{
            return [:]
        }
        
    }
    set{
        let data = NSKeyedArchiver.archivedData(withRootObject: newValue ?? [:])
        UserDefaults.standard.set(data, forKey: "timerDictionary")
    }
}

However my app crashes with 'NSInvalidArgumentException', reason: '-[__NSCFTimer encodeWithCoder:].

BigFire
  • 317
  • 1
  • 4
  • 17
  • 2
    `(NS)Timer` does not conform to `NS(Secure)Coding`. And what is the purpose to save entire `Timer` instances? Isn't `interval` and `repeating` and maybe `userInfo` sufficient? – vadian Jun 21 '21 at 08:18

1 Answers1

0

if you want to continue your timer when app becomes active again, the better approach will be to save yours timer last state (countdown or tick) and create new timer instance from saved state

efess
  • 81
  • 7
  • Have you tried the approach you are suggesting ? . do you have any sample code to prove it works? – BigFire Jun 21 '21 at 16:42