I have a UIAlertController that takes user input. I want to add the text the user input to an array and save that array in user default. The issue is, the newly entered text keeps replacing the previous entered text. So I think it's not saving in the array.
This is what I tried so far:
func presentAlert() {
let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
if let field = alertController.textFields {
// This is how I tried to create the array to hold input text
let textFieldArray = field as [UITextField]
let text = textFieldArray[0].text
var myArray = [""]
myArray.append(String(describing: text!))
UserDefaults.standard.set(myArray, forKey: "Gratitude")
UserDefaults.standard.synchronize()
print(myArray)
} else {
print()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
//textField.placeholder = ""
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
The mistake here is that creating a brand new array, appending one value, and writing it to UserDefaults
under the key "Gratitude" will always overwrite whatever is there and replace it with your single element array. If you would like to dynamically add additional elements to your stored array in UserDefaults
, you will have to access it first:
var myArray = UserDefaults.standard.array(forKey: "Gratitude") ?? []
myArray.append(String(describing: text!))
UserDefaults.standard.set(myArray, forKey: "Gratitude")
print(myArray)
I would also suggest storing your key in a constant so that you can be sure you're accessing the right value each time you request an object:
let myArrayKey = "Gratitude"
var myArray = UserDefaults.standard.array(forKey: myArrayKey) ?? []
myArray.append(String(describing: text!))
UserDefaults.standard.set(myArray, forKey: myArrayKey)
print(myArray)
Let me know if this makes sense.