Saved strings don't save when app closes

On File 1, I have 3 strings, all which save with the UserDefaults.standard.set line. On the same file / page, I have a text box that displays the threes strings. When I close the app and reopen, the same values are displayed. However, when I call the strings on File 2 / p age 2, the values do not display.

An explanation and code would be helpful. I am new to swift. Code:

//------file 1----------
@State var text: String = UserDefaults.standard.string(forKey: "TEXT_key") ?? ""
@State var inputText: String = ""
static var InText: String = UserDefaults.standard.string(forKey: "InText_key") ?? ""

TextField("Enter Text", text: $inputText)
text = inputText
File1.InText = text

Text("Saved Text: \(text)").lineLimit(3)
// Does display the text after app closed and reopened

//--------FILE 2--------

if let longitude = Double(File1.text), let latitude = Double(File1.text2) {
     let location = CLLocation(latitude: longitude, longitude: latitude)

// When I enter the values again on file1, it updates. but when I close and reopen, nothing shows. 

Excuse any syntax errors

Your File 1 and File 2 code seems to be disconnected as the variable names are different, so either you have modified the code or haven't show all of it.


When you write this line, are you sure File1.text and File1.text2 are both strings that can be converted into a Double (a number)?:

if let longitude = Double(File1.text), let latitude = Double(File1.text2) {

If these values are simple strings, like "Hello", and not a string of a number, like "10.5", then the above line of code will fail and everything inside of the if statement will not be run.



Here is an example of what you could to instead which would make sure the latitude and longitude values are both numbers and not random strings:

  • You can use the @AppStorage property wrapper to automatically read and write a value to UserDefaults.
  • You can then use the TextField initialiser that accepts a number as a binding and will automatically handle the conversion between String and Double for you.
  • You can then use these Double values straight away and pass them to CLLocation without any problems with optionals and String-Double conversion.
@AppStorage("latitude") private var latitude: Double = 0
@AppStorage("longitude") private var longitude: Double = 0

TextField("Latitude", value: $latitude, format: .number)
TextField("Longitude", value: $longitude, format: .number)

// add this modifier to text fields to only allow numbers to be entered
.keyboardType(.decimalPad)

// this will work always so use wherever
CLLocation(latitude: latitude, longitude: longitude)


Hopefully this helps and points you to a better solution.

Please show where you save strings in UserDefaults.

Saved strings don't save when app closes
 
 
Q