I’m utilizing a category conforming to ObservableObject
to retailer places. I’ve used @AppStorage
to persist an array of places chosen by a consumer.
class SavedLocations: ObservableObject {
@AppStorage("Places") var all = [Location]()
func deleteLocation(at offsets: IndexSet) {
all.take away(atOffsets: offsets)
}
}
The category above is first instantiated utilizing @StateObject
in a menu that shows chosen places (if any) and a sheet which can be utilized to seek for new places so as to add.
struct LocationView: View {
@Surroundings(.dismiss) var dismiss
@ObservedObject var networking: Networking
@StateObject var savedLocations = SavedLocations()
@State non-public var showingSheet = false
var physique: some View {
NavigationView{
VStack {
// the record of all location, not all the time refreshed when up to date utilizing LocationSearch sheet presentation
Listing {
ForEach(savedLocations.all, id: .self) { saved in
Button(saved.title) {
// use the chosen location
dismiss()
}
}
.onDelete(carry out: savedLocations.deleteLocation)
}
}
.sheet(isPresented: $showingSheet) {
LocationSearch(networking: networking)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button{
showingSheet.toggle()
} label: {
Label("New Location", systemImage: "plus")
}
}
}
.navigationTitle("Places")
}
}
}
If a consumer searches for a location, they’re offered with an inventory of places as proven beneath:
struct LocationSearch: View {
@Surroundings(.dismiss) var dismiss
@StateObject var locationService = LocationService()
@ObservedObject var networking: Networking
@ObservedObject var savedLocations = SavedLocations()
@State var showAlert = false
var physique: some View{
Type {
...
Part {
Listing {
ForEach(locationService.searchResults, id: .self) { completionResult in
Button("(completionResult.metropolis), (completionResult.nation)") {
networking.getCoordinate(addressString: completionResult.metropolis) { coordinates, error in
if error == nil {
networking.lastLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
DispatchQueue.most important.async() {
let newLocation = Location(title: completionResult.metropolis)
// UPDATES not all the time mirrored when sheet is dismissed
savedLocations.all.append(newLocation)
savedLocations.all = savedLocations.all.distinctive()
dismiss()
}
} else {
print("Error setting customized location: (String(describing: error))")
showAlert.toggle()
}
}
}
}
}
}
}
}
}
The issue is that upon dismissing the sheet used to seek for and add places, the brand new location doesn’t all the time instantly seem within the record of all places. Normally it does seem instantly after the search sheet is dismissed, however often it’s essential to dismiss each sheets and set off a brand new occasion of the sheet containing the record of all places.
I primarily based my strategy off of this publish.