I am getting an error when trying to fetch objects in SwiftUi in a form sheet modal in iOS 13.
Here's the error:
[SwiftUI] Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x600003218620>
I am able to run a fetchRequest from a list view, but not in the modal.
Has anyone else seen this issue?
I set the Environment context in the SceneDelegate:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//managedObjectContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(sampleViewModel).environmenbject(customerViewModel).environment(\.managedObjectContext, managedObjectContext))
self.window = window
window.makeKeyAndVisible()
In the ContentView:
import SwiftUI
struct ContentView: View {
@State var isPresented = false
var body: some View {
NavigationView {
VStack {
// Search bar, filter, and divider
SampleListView()
}
.sheet(isPresented: $isPresented) {
NewSampleView()
}
.navigationBarTitle("Samples")
AddSampleButton(isNewSamplePresented: $isPresented)
}
}
}
Able to see items in the SampleListView:
struct SampleListView: View {
@EnvironmentObject var viewModel: SampleListViewModel
@FetchRequest(fetchRequest: Sample.allSamplesFetchRequest()) var samples: FetchedResults
var body: some View {
List(self.samples) { sample in
VStack(alignment: HorizontalAlignment.leading) {
NavigationLink(destination: SampleView(activeSampleModel: ActiveSampleViewModel(sample: sample))) {
Spacer()
Text(sample.trackingNumber ?? "")
Spacer()
Text(sample.sampleId ?? "")
Spacer()
}
}
}
}
}
But I get the error when presenting the NewSampleView (I've tried using a fetchRequest defined in the view as well as one defined in the NSManagedObject subclass but the fetch is always failing with the above error) :
import SwiftUI
import CoreData
struct NewSampleView : View {
@State var customerId = ""
@State var sampleDate = Date(timeIntervalSinceNow: 0)
@State var receiptDate = Date(timeIntervalSinceNow: 0)
@State var customerServiceSampleNumber = ""
@State var notes = ""
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: fetchRequest(), animation: nil) var customers: FetchedResults
var body: some View {
List(self.customers) { customer in
VStack(alignment: HorizontalAlignment.leading) {
Spacer()
Text(customer.customerId ?? "")
Spacer()
}
}
}
static func fetchRequest() -> NSFetchRequest {
let request: NSFetchRequest = Customer.fetchRequest() as! NSFetchRequest
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
return request
}