Reputation: 91
The output that I am trying to achieve is to save the in game currency so that it's still available when the user re-opens the app. When the user collects more currency, I would like the collected currency to be added to the total currency.
With the code that I have, the currency doesn't save when the app is re-opened.
I am still learning swift so any help / advice would be greatly appreciated!
let totalCoinDefault = UserDefaults.standard()
totalCoins = totalCoinDefault.integer(forKey: "Totalcoin")
totalCoinLabel.text = "\(self.totalCoins)"
func currencyUpdate(_ currentTime: CFTimeInterval){
if ( coin > 0) {
totalCoins += self.coin
totalCoinLabel.text = NSString(format: "Totalcoin : %i", totalCoins) as String
let totalcoinDefault = UserDefaults.standard()
totalcoinDefault.setValue(totalCoins, forKey: "Totalcoin")
totalcoinDefault.synchronize()
}
}
Upvotes: 0
Views: 186
Reputation: 5056
You can use this:
let totalCoinDefault = UserDefaults.standard()
totalCoins = totalCoinDefault.integer(forKey: "Totalcoin")
totalCoinLabel.text = "\(self.totalCoins)"
if ( coin > 0) {
totalCoins += self.coin
totalCoinLabel.text = String(format: "Totalcoin : %i",totalCoins)
totalcoinDefault.setValue(totalCoins, forKey: "Totalcoin")
totalcoinDefault.synchronize()
}
You don't need this func.
Upvotes: 1