Trying to implement/learn keychain use in iOS. I have saved multiple values of a struct in Keychain but while retrieving values it is showing nil. Testing the code in Simulator only. This is the generic keychain read method:
extension KeychainHelper{
func read<T>(service: String, account: String, type: T.Type) -> T? where T : Codable {
// Read item data from keychain
guard let data = read(service: service, account: account) else {
return nil
}
// Decode JSON data to object
do {
let item = try JSONDecoder().decode(type, from: data)
return item
} catch {
assertionFailure("Fail to decode item for keychain: \(error)")
return nil
}}}
The full code of KeychainHelper class can be found here full keychainhelper class (can be replicated easily) when I am calling the API the code is working fine showing values also
class ViewModel : ObservableObject{
//some published var like centerService
let token = response.ResponseData.AuthToken
//other var
let userDetails = Pass(authToken:token, other vars)
KeychainHelper.standard.save(userDetails,service,account)
}
But when I am trying to read keychain from different func it is showing nil. This is the call:
class checkStatus{
var userStatus = ViewModel()
let userDetails = KeychainHelper.standard.read(service: userStatus.centerService,
account:userStatus.centerAccount, Pass.self)
}
The error is Operation failed with status -25299. Pass definition:
struct Pass:Codable{
let authToken:String
let centerID:String
let userID:String
let accessID:Int
}