Whether you’re building your own custom backend, integrating with Firebase, or authenticating through Facebook at some point your app may need to save a security token somewhere.
NSUserDefaults is the wrong way. The Security Framework has got you covered.
The keychain is different from NSUserDefaults. The data is encrypted by iOS, and the information can’t be read by other apps. Retrieving data from the keychain is done using a query interface.
var query = [String: Any]()
query[kSecClass as String] = kSecClassInternetPassword
query[kSecAttrAccount as String] = "com.app.foo.bar.token"
query[kSecAttrServer as String] = "my.apps.backend.com"
query[kSecValueData as String] = "<token-data>".data(using: .utf8)
Followed by a call to one of these functions
SecItemDelete(query as CFDictionary)
SecItemAdd(query as CFDictionary, nil)
SecItemCopyMatching(query as CFDictionary, &item)