I have an object that contains sensitive data like pin code and password, and it is saved in user defaults as Data.
Is saving an object as Data in user defaults is a safe decision, or would it be better to save the user object in keychain?
All sensitive information must stay in the Keychain, UserDefaults is easily accessible for anyone trying to debug your app.
There are some frameworks to help you work with Keychain, like KeychainAccess.
Using the framework given above, you can save encoded information using a Codable model.
let keychain = Keychain(service: "Service")
if let value = newValue, let data = try? JSONEncoder().encode(value) {
try? keychain.set(data, key: "Key")
}
and to retrieve:
let keychain = Keychain(service: "Service")
if let data = try? keychain.getData("Key") {
return try? JSONDecoder().decode(Model.self, from: data)
}