简体   繁体   中英

Swift KeyChain store custom object

I'm trying to save something like this:

struct User {
    var id: String? = nil
    var name: String? = nil
    var cellPhone: String? = nil
    var email: String? = nil
}

Into the KeyChain , according to my current project's guidelines, all of these data is sensitive but the email, so I'm trying to store all of these data into the KeyChain for this reason.

Is there any way that I can store the whole object? Or should I just trust CoreData to store these objects? I need to store them in the device to verify if the user has already registered to skip the registration process and take them to the app's main screen.

I'm using the KeyChainWrapper methods like this one:

let saveSuccessful: Bool = KeychainWrapper.standard.set("Some String", forKey: "myKey")

But if I pass my User instance, I get:

No exact matches in call to instance method 'set'

Which I believe is because there's no support either from the KeyChainWrapper or KeyChain itself to save a custom object into it.

Been trying to find what kind of data types we can store inside KeyChain , maybe it's just primitives?

I managed to solve my issue, after looking a little bit more into the .set() options for the KeyChainWrapper I found one for Data type.

So, what I'm doing now is:

let encodedUser = jsonUtils.encode(object: user)
KeychainWrapper.standard[.userKey] = encodedUser

And in my JSONUtils class I have encode and decode functions, so I can convert my User into Data and viceversa

static let shared = JSONUtilities()

func encode<T: Codable>(object: T) -> Data? {
    do {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        return try encoder.encode(object)
    } catch let error {
        print(error.localizedDescription)
    }
    return nil
}

func decode<T: Decodable>(json: Data, as clazz: T.Type) -> T? {
    do {
        let decoder = JSONDecoder()
        let data = try decoder.decode(T.self, from: json)
        
        return data
    } catch {
        print("An error occurred while parsing JSON")
    }
    
    return nil
}

This way I can store my User object securely into the KeyChain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM