'Why is Xcode crashing when I try to preview?

Every time I am trying to resume my preview canvas in Xcode I get this annoying error. I tried restarting, moving the project to another location, and changing the preview device. The current project is a fresh one, just started building a view.

Strange thing is that when I run it on the iOS Simulator it works. The app builds successfully. I also noticed that this is only happening when I use source control with my project(GitHub). Not using it is not an option for me.

Let me know if I need to add the whole crash report, because it's very long.

Here is the full crash log https://developer.apple.com/forums/content/attachment/5f8f5c96-7c1e-4eef-b0d7-ed59894a9c30

error screenshot



Solution 1:[1]

You didn't add your code so I can't help specifically but here are some of the reasons it happened to me in the past:

  • If you use an environment object on the view you're previewing and you don't add it to preview, it causes a crash:

    struct MyView_Previews: PreviewProvider {
        static var previews: some View {
            MyView()
                .environmentObject(ViewModel())
        }
    }
    
  • Sometimes I just add ZStack to it and it magically solves the problem:

    struct MyView_Previews: PreviewProvider {
        static var previews: some View {
            ZStack {
                MyView()
            }  
        }
    }
    
  • Sometimes It helps to clean the project (command + shift + K) and build again

Basically if your project works in simulator it means there's nothing wrong with it, it builds. The only problem is that you can't use the preview. You probably didn't set it right, it's missing something it needs in order to run properly. Try to figure it out. Or just run on simulator like we did before there was such a thing as previews..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1