Xcode 12 & SwiftUI: Cannot preview in this file — Failed to update preview

Viewed 9948

Seems like previews stopped working on Xcode 12! Trying to preview the SwiftUI file template and getting the error below. Any ideas how to fix this? Tried cleaning the build folder, deleting derived data and restarting Xcode to no avail!

On Catalina 10.15.6.

RemoteHumanReadableError: Failed to update preview.

The preview process appears to have crashed.

Error encountered when sending 'prepare' message to agent.

==================================

|  RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)
|  
|  BSServiceConnectionErrorDomain (3):
|  ==BSErrorCodeDescription: OperationFailed

The code I am trying to preview (from SwiftUI new file template):

import SwiftUI

struct SwiftUIView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}
6 Answers

If your SwiftUIView use ObservableObject as environmentObject, try this:

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView().environmentObject(YourObservableObjectClass())
    }
}

if you use SwiftUI (ObservableObject, @EnvironmentObject)

add to previews

.environmentObject(ModelData())

--

struct LandmarkDetail_Previews: PreviewProvider {
        static var previews: some View {
    
            LandmarkDetail(landmark: ModelData().landmarks[1])
                .environmentObject(ModelData())
        }
    }

my ModelData

final class ModelData:ObservableObject
{
   @Published var landmarks: [Landmark] = load("landmarkData.json")
}

SwiftUI preview error

Hello everyone. I managed to solve this problem. It is enough to comment everything in the didFinishLaunchingWithOptions method and preview SwiftUI will work. Solution

Error: Cannot preview in this file

The answer by kerim.ba worked for me:

Did you try to erase Xcode Application state beside the derived data? The Xcode Application State is saved on path ~/Library/Saved\ Application\ State/com.apple.dt.Xcode.savedState – kerim.ba

I had the same issue when I updated Firebase Analytics (to v6.33.0). Commenting out the following line fixed it.

FirebaseApp.configure()
Related