0

The structure stores the date value in the Date? format, but after saving it returns it in the timestamp format.

if let data = try? JSONEncoder().encode(contact),
     let dict = try? JSONSerialization.jsonObject(with: data, options: .Element.fragmentsAllowed) {
            defaults.set(
            dict,
            forKey: "contact")
    }
    print(defaults.object(forKey: "contact"))
}

Please tell me how can I save the date in Date format. In this case, it is necessary to preserve the entire structure.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Vladislav
  • 11
  • 1

1 Answers1

0

As allready pointed out JSON does not support the Date type. It will encode it to an integer by default.

But it seems you want to decode it back and use it again as Date. This is possible by using the JSONDecoder().

let decoded = try JSONDecoder().decode("of whatever type the encoded object was here".self, data: data)

and you got the same object back that you encoded.

And by the way you don´t need to use JSONSerialization to store your object in UserDefaults you can store the data directly.

UserDefaults.standard.set(data, forKey: "contact")

and retrieving the data:

let data = UserDefaults.standard.data(forKey: "contact")

and decoding it like i´ve shown above.

burnsi
  • 6,194
  • 13
  • 17
  • 27