0

I want to update the view with data when a view is opened so I added:

.onAppear {
    loadData()
}

But I only want to update it once when the view gets opened not every time it gets reopened e.g. with a back button.

--> Only update on App start

1 Answers1

0

You can put the value in UserDefaults so you will know in the second load that you have already performed loading.

extension UserDefaults {
    
    var firstTimeVisit: Bool {
        get {
            return UserDefaults.standard.value(forKey: "firstTimeVisit") as? Bool ?? true
        } set {
            UserDefaults.standard.setValue(newValue, forKey: "firstTimeVisit")
        }
    }
    
}

struct ContentView: View {
    
    var body: some View {
        VStack {
            
        }.task {
            if UserDefaults.standard.firstTimeVisit {
                // load Data
                UserDefaults.standard.firstTimeVisit = false
            } 
        }
    }
}

UPDATE:

extension UserDefaults {
    
    var firstTimeVisit: Bool {
        get {
            return !UserDefaults.standard.bool(forKey: "firstTimeVisit")
        } set {
            
            UserDefaults.standard.set(newValue, forKey: "firstTimeVisit")
        }
    }
    
}
azamsharp
  • 19,710
  • 36
  • 144
  • 222
  • Please do not suggest KVC with `UserDefaults`. There is `bool(forKey:` and `set(_:forKey:`) – vadian Oct 01 '22 at 07:35
  • Good morning, I‘m new in swift. Why is KVC not good or what is the alternative to @azamsharp‘s code? – Social Processing Oct 01 '22 at 09:29
  • @SocialProcessing vadian mentioned that in his comment. Note that this solution will set the property once and store it so next time the app is started nothing will be downloaded so you will need some logic to handle that as well in case it’s a new day. – Joakim Danielson Oct 01 '22 at 09:55