I have a problem with SwiftUI Preview not working sometimes (but not giving me any errors, just a blank Canvas). I have narrowed down the problem - it doesn't work when I'm using fetchRequest with init. But I don't know what to do next.
Preview works with this code:
import SwiftUI
struct ListView: View {
var fetchRequest = FetchRequest<NPBooking>(entity: NPBooking.entity(), sortDescriptors: [])
var bookings: FetchedResults<NPBooking> { fetchRequest.wrappedValue }
var body: some View {
ForEach(bookings, id: \.self) { booking in
Text("item")
}
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let testBooking = NPBooking.init(context: context)
testBooking.date = Date()
testBooking.name = "name"
return ListView().environment(\.managedObjectContext, context)
}
}
Preview doesn't work with this code:
import SwiftUI
struct ListView: View {
var fetchRequest: FetchRequest<NPBooking>
var bookings: FetchedResults<NPBooking> { fetchRequest.wrappedValue }
var body: some View {
ForEach(bookings, id: \.self) { booking in
Text("item")
}
}
init(startDateOfMonth: Date) {
fetchRequest = FetchRequest<NPBooking>(entity: NPBooking.entity(), sortDescriptors: [
NSSortDescriptor(keyPath: \NPBooking.date, ascending: true)
], predicate: NSPredicate(format: "date >= %@", startDateOfMonth as NSDate))
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let testBooking = NPBooking.init(context: context)
testBooking.date = Date()
testBooking.name = "name"
return ListView(startDateOfMonth: Date()).environment(\.managedObjectContext, context)
}
}
I guess I need to add some test data for this init or fetchRequest or both? Tried few things and I cannot manage to make it work.