My project has an alert button with a UITextField that allows me to input a String that is then appended to an array that I have declared globally. This addition allows another UITextField to show the addition in its drop down menu. However, the changes will only save for the time the app remains open, and will not save when I try to configure UserDefaults.
I've read through what looked like similar S.O. postings, but I am unable to get any of the solutions to work with my issue.
(This is declared globally.)
let defaults = UserDefaults.standard
(This is also global.)
var needIndicatorArray: [String] = ["SNAP", "EBT", "FVRX"]
(This is the code I'm using to append the above mentioned array. This code will append the array, but will not save the addition after the app is closed and re-opened.)
@IBAction func addNeedIndicator(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add Need Indicator", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
//This should append the global array once the user hits the add item on the UIAlert
self.needIndicatorArray.append(textField.text!)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new item"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
You need to save to User Defaults and then read back the array when needed.
I have just included the relevant section below, when you should save to User Defaults:
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
// This should append the global array once the user hits the add item on the UIAlert
self.needIndicatorArray.append(textField.text!)
// You need to save to User Defaults
defaults.set(needIndicatorArray, forKey: "yourKey")
}
When you need to retrieve the array, use this:
let array = defaults.object(forKey: "yourKey") as? [String] ?? [String]()