I am trying to get all records from Entity Location and pull the data from the entity to create a array of strings and display in a MenuPicker. In getLocationNames() ForEach statement it never pulls locations even though there are records. Also I do have a warning on that line: Result of 'ForEach<Data, ID, Content>' initializer is unused
entity: Location.entity(),
sortDescriptors: [NSSortDescriptor(key: "locationName", ascending: true)]
) var locations: FetchedResults<Location>
@State private var locationNames: [String] = []
@State private var locationDetails:[String] = []
@State private var selectedLocation: String? = nil
@State private var location: Location? = nil
var body: some View {
NavigationView {
ScrollView (showsIndicators: false) {
HStack {
Text("Select Location")
Picker("Location", selection: $selectedLocation , content: {
ForEach(locationNames,id: \.self, content: { locationName in
Text(locationName )
})
})
.pickerStyle(MenuPickerStyle())
.onReceive([self.selectedLocation].publisher.first()) { value in
selectedLocation = value
print("selectedLocation: \(selectedLocation ?? "not found")")
}
.onTapGesture {
// self.callWeatherAPI(location: selectedLocation)
self.getLocationNames()
}
Section{
if ($selectedLocation.wrappedValue != nil) {
}
}
header: {
Text("**Current Weather**")
.padding(.top, 10)
}
}
.navigationTitle("Weather")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
// Button("Save", action: { Task { try? await rI?(nameInput, phoneInput) } })
Button("Detail", action: { onAdd()
} )
.foregroundColor(.blue)
}
}
}
.onAppear{
self.getLocationNames()
}
}
}
func getLocationNames() -> (Void){
ForEach(locations) { location in
locationNames.append( self.getLocationString(location: location))
}
}
private func getLocationString(location: Location) -> String {
var locDetails: String = location.locationType! + "; "
locDetails += location.locationName! + ", "
locDetails += location.zip!
return locDetails
}
}