JamesG
JamesG

Reputation: 1601

Swift + Locksmith: Not storing value

I am trying to store a value at the end of a game.

I am using the https://github.com/matthewpalmer/Locksmith updateData method.

It says on the Github Repo

as well as replacing existing data, this writes data to the keychain if it does not exist already

try Locksmith.updateData(["some key": "another value"], forUserAccount: "myUserAccount")

This is what I have:

let dictionary = Locksmith.loadDataForUserAccount("gameKeyChainValues")
                            
print("Ended \(EndDateAndTimeString)")

do {
   try Locksmith.updateData(["BattleEnd": "12345678"], forUserAccount: "gameKeyChainValues")
                                
}
catch {
    print("Unable to set time")
}

print("This line ran")
                            
if let timeBattleEnded = dictionary!["BattleEnd"] as? String {
    print("Stored for END: \(timeBattleEnded)")
}

This line print("Ended (EndDateAndTimeString)") outputs:

Ended 19:33:38+2016-08-05

This line print("Unable to set time") does nothing

This line print("This line ran") outputs:

This line ran

This line: print("Stored for END: (timeBattleEnded)") does nothing.

When I set a break point and then type po dictionary in the console it shows me other things that are set but not this value.

Can anyone see why?

EDIT:

So, After checking the console. It does appear that directly after I save the information to the Keychain it is there. Then I switch views and update another item in the keychain. This then seems to delete the original one and only keep the new item. Both have different names.

Any ideas?

Upvotes: 5

Views: 1024

Answers (2)

MarkP
MarkP

Reputation: 2566

In the exact words of matthew palmer:

Only one piece of data is stored under an account, so when you call updateData it will overwrite whatever's currently stored for that account

so, Everytime you call Locksmith.updateData it basically clears all the data in there and then adds the new value. You need to send both keys and values together.

Try this:

try Locksmith.updateData(["BattleEnd": "12345678", "Key2": "Value Two"], forUserAccount: "gameKeyChainValues")

Upvotes: 3

Jim
Jim

Reputation: 73936

The dictionary you fetch in the first line isn't a constantly updating view of the keychain, it's just a copy of what's in the keychain when you call that method. It won't be updated when you update the keychain. If you want the up to date values out of the keychain after you update it, call loadDataForUserAccount() again after you update it.

Upvotes: 1

Related Questions