Global Data with UserDefaults - Swift
I want to keep a String forever and access it across multiple front-end controllers using global data. This is my code to set the string on button click.
All codes below are found on interface controller 1
UserDefaults.standard.set("yellow", forKey: "newBingoColor")
This code is shown in the "Wake up with context" section:
override func awake(withContext context: Any?) {
super.awake(withContext: context)
let newBingoColorObject = UserDefaults.standard.object(forKey: "newBingoColor")
if let newBingoColor = newBingoColorObject as? String {
temporaryVars.newBingoColor = newBingoColor as! String
print(newBingoColor)
print(temporaryVars.newBingoColor)
}
The problem is that the string is saved in temporaryVars.newBingoColor
and I can see it on the interface of Controler 2, but when I restart the program it temporaryVars.newBingoColor
prints like nothing in the interface controller 2. If I try to view it on the interface of Controller 1 even though it is displayed fine?
What's wrong here?
source to share
In your AppDelegate app add this line of code to your function applicationDidEnterBackground
:
UserDefaults.standard.synchronize()
And also add the same line after installing such a key:
UserDefaults.standard.set("yellow", forKey: "newBingoColor")
UserDefaults.standard.synchronize()
source to share