I am trying to update a game score in the Keychain using the popular library: Locksmith.
In my Initial ViewController viewDidLoad()
I have this code to initially set the value to: 0
do {
try Locksmith.saveData(data:["score" : 0], forUserAccount: "some_unique_game_name")
} catch {
print("Error")
}
In my second ViewController, I have initialised the keychain item at the top like so:
let keychain_data = Locksmith.loadDataForUserAccount(userAccount: "some_unique_game_name")
and then in a function to retrieve the score I have this code:
NSLog("Score is: \(self.keychain_data!["score"])").
This returns in the console:
Score is: 0
Now, I have another function that sets the game score like so:
func updateScor(to: score) {
NSlog("score is: \(score)")
do {
try Locksmith.updateData(data:["score" : score], forUserAccount: "some_unique_game_name")
} catch {
print("Error")
}
NSlog("saved score is: \(score)")
}
Which gives me in the Log:
score is: 9999
saved score is: 9999
Now, when I play the game again the score value is still set as:
Score is: 0
(This is without going back to the initial view controller that sets it as 0).
It should be: 9999
Any ideas?
It seem you are trying to print from the old value.
Once you update the data, you should get the data back from the keyChains to get the latest copy from there.
Your code should be in the following manner
1) Set the score to 0 in viewDidLoad()
2) Get the kechain_data and print, you will see 0
var keychain_data = Locksmith.loadDataForUserAccount(userAccount: "some_unique_game_name")
NSLog("Score is: \(self.keychain_data!["score"])")
3) set your score with updateScor(to: 9999)
4) Again get the keychain_data and then try NSLog
keychain_data = Locksmith.loadDataForUserAccount(userAccount: "some_unique_game_name")
NSLog("Score is: \(self.keychain_data!["score"])")
Hope it helps!