1

So I have an app like the landmark app from apple.

I'm trying to figure out how to save the favorites, but I'm struggling with it.

I tried with save() and with userDefaults but with no result.

Some solutions use Toggle(isOn:), but the code doesn't use this.

The code from the landmark app is:

Button(action: {
   self.userData.landmarks[self.landmarkIndex]
      .isFavorite.toggle()
}) {
   if self.userData.landmarks[self.landmarkIndex]
      .isFavorite {
      Image(systemName: "star.fill")
         .foregroundColor(Color.yellow)
   } else {
      Image(systemName: "star")
         .foregroundColor(Color.gray)
   }
}

One of my attempts was the following:

Button(action: {
                    UserDefaults.standard.set(self.userData.landmarks[self.landmarkIndex]
                        .isFavorite.toggle(self.isFavorite, forKey: Bool)
                    )
                }) {
                    if UserDefaults.standard.set(self.userData.landmarks[self.landmarkIndex])
                        .isFavorite {
                        Image(systemName: "star.fill")
                            .foregroundColor(Color.yellow)

                        } else {
                        Image(systemName: "star")
                            .foregroundColor(Color.gray)
                    }

I get an error 'Type of expression is ambiguous without more context'.

The button action is embedded in a navigationbaritem.

the code for userData is in the UserData.swift file:

import SwiftUI

final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var landmarks = landmarkData
}

and

@EnvironmentObject var userData: UserData

is used in the landmarkdetail.swift file where the button action is placed

  • The code you've put here is for showing whether landmarks are favorites, not saving them. Please edit your question to include that code (you will probably also need to put up the code for `UserData` (assuming that's the name of the type of the `userData` variable)). – Sam Apr 27 '20 at 21:38
  • Edited my question – andy verhaegen Apr 29 '20 at 17:30
  • 1
    What is the `save()` function you mentioned? – Sam Apr 30 '20 at 12:38
  • I tried with core data which uses managedObjectContext.save(), but with no result – andy verhaegen May 17 '20 at 17:12

0 Answers0