I have two views:
The parent view first decodes a bundled JSON file and then passes an object to the child view. The child view then saves the object (plus a couple additional objects) to Core Data.
That part works fine. The problem is that after saving to Core Data, the child view then navigates back to the parent view and I'm not sure why. Intended behaviour is to navigate back to the root view.
Parent View:
struct SelectCityView: View {
@State private var cities = [Destination]()
@State private var searchText: String = ""
var body: some View {
VStack {
SearchBar(text: $searchText)
List {
// Filter decoded array by search text
ForEach(cities.filter{self.searchFor($0.city)}.sorted(by: { $0.city < $1.city })) { destination in
// Here's where the parent view passes the object to the child view
NavigationLink(destination: SelectTravelDatesView(selectedCity: destination)) {
Text("\(destination.city), \(destination.country)")
}
}
}.id(UUID())
}.navigationTitle("Select city")
.onAppear(perform: {
// Decode JSON data from bundle
cities = Bundle.main.decode([Destination].self, from: "cities.json")
})
}
private func searchFor(_ searchQuery: String) -> Bool {
return (searchQuery.lowercased(with: .current).hasPrefix(searchText.lowercased(with: .current)) || searchText.isEmpty)
}
}
Child View:
struct SelectTravelDatesView: View {
@Environment(\.managedObjectContext) private var viewContext
@State var selectedCity: Destination?
@State private var startDate = Date()
@State private var endDate = Date()
var body: some View {
Form {
Section(header: Text("Trip start date")) {
DatePicker(selection: $startDate, in: Date()..., displayedComponents: .date) {
Text("Trip start date")
}.datePickerStyle(GraphicalDatePickerStyle())
}
Section(header: Text("Trip end date")) {
DatePicker(selection: $endDate, in: startDate..., displayedComponents: .date) {
Text("Trip start date")
}.datePickerStyle(GraphicalDatePickerStyle())
}
}.navigationTitle("Select dates")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
// Save to Core Data
Button(action: {
addItem()
}, label: {
Text("Save")
})
}
}
}
private func addItem() {
withAnimation {
let newItem = Trip(context: viewContext)
if let destination = selectedCity {
newItem.timestamp = Date()
newItem.destination = destination.city
newItem.startDate = startDate
newItem.endDate = endDate
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
}
Any help would be greatly appreciated.