Junior — Middle
Where and how should user confidential information be stored?
sobes.tech AI
Answer from AI
User confidential information (passwords, tokens, personal data) on iOS should be stored in Keychain — a secure storage provided by the system for safely saving secrets.
Keychain encrypts data and ensures access only to your app (or group of apps if configured).
Example of saving and retrieving a string in Keychain using Swift:
import Security
func saveToKeychain(key: String, data: Data) -> Bool {
let query = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data
] as [String : Any]
SecItemDelete(query as CFDictionary) // Delete old item if exists
let status = SecItemAdd(query as CFDictionary, nil)
return status == errSecSuccess
}
func loadFromKeychain(key: String) -> Data? {
let query = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue!,
kSecMatchLimit as String: kSecMatchLimitOne
] as [String : Any]
var dataTypeRef: AnyObject? = nil
let status = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == errSecSuccess {
return dataTypeRef as? Data
}
return nil
}
Thus, confidential data is stored securely and accessible only to the app.