Vlad Poncea
Vlad Poncea

Reputation: 359

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

Upvotes: 4

Views: 3205

Answers (3)

Gulov Khurshed
Gulov Khurshed

Reputation: 71

Encountered such issue and after searching found that problem in difference on assigning files to app and test targets.

I have created new files for holding business logic and moved logic from View files there after which previews start crashing. After investigation found that newly created files are assigned in Target Membership field to current project module, but not assigned to UI tests target. Checked UI tests target for this files and preview started to work again.enter image description here

Upvotes: 0

Brian
Brian

Reputation: 35

It may be late, but this is the correct answer:

You have to expose your Preview to the Environment variable.

You do that by adding the modifier

 .environment(ViewModel()) // if ViewModel is the observable object// 

to the Preview view that it is displaying e.g.,

#Preview {
   ContentView()
      .environment(ViewModel())
}

Upvotes: 1

Gal
Gal

Reputation: 546

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..

Upvotes: 6

Related Questions