SwiftUI with Core Data getting Blank Screen in simulator in Xcode 12

Viewed 1436

In XCode 12, if I create a new SwiftUI App and check the "Use Core Data" button, the resulting application (with no changes) shows a blank screen in simulator (as well as on a device). In preview it shows the example timestamps as expected. Why are the simulator/device not showing the example timestamps?

4 Answers

The toolbar items default code is broken in SwiftUI: Use this in the template code. Embed the List into a NavigationView and then The buttons in a HStack.

var body: some View {
    NavigationView { //added
    List {
        ForEach(items) { item in
            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
        }
        .onDelete(perform: deleteItems)
    } .toolbar {
        
                    #if os(iOS)
                    HStack {  //added
                        EditButton()
                        Button(action: addItem) {
                            Label("Add Item", systemImage: "plus")
                        }
                    }//added
                    #endif

    }
    }//added NavView embed
}

Also to get the preview to work you need to change the PersistenceController to shared not preview.

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
    }
}

If you want to see the sample inputs from the template (10 rows with timestamp) in your simulator, you need to change in App.swift:

let persistenceController = PersistenceController.shared

to

let persistenceController = PersistenceController.preview

Without this change, the template provided by Apple shows the sample input only in the canvas preview of ContentView. The Persistence.swift file has two static variables: shared and preview. The .shared one is just initiating an (empty) PersistenceController while the .preview static variable initiates a PersistenceController, adds ten items with the current time stamp to the viewContext and saves it.

Clearing the data in the simulator did not work for me.

I'm struggling with .toolbar but find it only works with a NavigationView in the released XCode 12.

So if you're using the template that comes when you click to use Core Data, just add to the ContentView.

clearing the data in simulator under "Device->Erase all content and settings" worked for me

Related