skip to Main Content

I created a new SwiftUI project but the code will not load in the live preview window I get the following error every time:

Cannot preview in this file -. but when I run it on simulator it works good also for other views it works.

enter image description here

This is the code

import SwiftUI
import FirebaseAuth


class AppViewModel: ObservableObject {
    
    let auth = Auth.auth()
    
    @Published var LoggedIn = false
    
    var isLoggedIn: Bool{
        return auth.currentUser != nil
    }
    
    func LogIn(email: String, password: String) {
        
        auth.signIn(withEmail: email, password: password) { [weak self] result, error in
            guard result != nil, error == nil else{
                return
            }
            
            DispatchQueue.main.async {
            // Success
            self?.LoggedIn = true
            }
        }
        
    }
    
    func SignUp(email: String, password: String) {
        
        auth.createUser(withEmail: email, password: password) { [weak self] result, error in
            guard result != nil, error == nil else{
                return
            }
            DispatchQueue.main.async {
            // Success
            self?.LoggedIn = true
            }
        }
        
    }
}

struct ContentView: View {
    @EnvironmentObject var ViewModel : AppViewModel
    var body: some View {
        NavigationView {
        if ViewModel.LoggedIn {
            Text ("You are Logged In")
            } else{
                LogInView()
        }
    }
        .onAppear {
            ViewModel.LoggedIn = ViewModel.isLoggedIn
        }
    }
}

struct LogInView: View {
    @State var email = ""
    @State var password = ""
    
    @EnvironmentObject var ViewModel : AppViewModel
    var body: some View {
        
        VStack {
            
            TextField("Email Adress", text: $email)
                .disableAutocorrection(true)
                .autocapitalization(.none)
                .padding()
                .background(Color(.secondarySystemBackground))
                .cornerRadius(15)
            
            SecureField("Password", text: $password)
                .disableAutocorrection(true)
                .autocapitalization(.none)
                .padding()
                .background(Color(.secondarySystemBackground))
                .cornerRadius(15)
            
            Button(action: {
                
                guard !email.isEmpty, !password.isEmpty else{
                    return
                }
                ViewModel.LogIn(email: email, password: password)
            }) {
                Text("Log In")
                    .foregroundColor(Color.white)
                    .font(.headline)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(Color.accentColor)
                    .cornerRadius(20.0)
            }
            
            NavigationLink("Create an account", destination: SignUpView())
                .padding()
            

            
        }
        .padding(.horizontal, 24.0)
        .navigationTitle("Welcome")
    }
}


struct SignUpView: View {
    @State var email = ""
    @State var password = ""
    
    @EnvironmentObject var ViewModel : AppViewModel
    var body: some View {
        
        VStack {
            
            TextField("Email Adress", text: $email)
                .disableAutocorrection(true)
                .autocapitalization(.none)
                .padding()
                .background(Color(.secondarySystemBackground))
                .cornerRadius(15)
            
            SecureField("Password", text: $password)
                .disableAutocorrection(true)
                .autocapitalization(.none)
                .padding()
                .background(Color(.secondarySystemBackground))
                .cornerRadius(15)
            
            Button(action: {
                
                guard !email.isEmpty, !password.isEmpty else{
                    return
                }
                ViewModel.SignUp(email: email, password: password)
            }) {
                Text("Sign Up")
                    .foregroundColor(Color.white)
                    .font(.headline)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(Color.accentColor)
                    .cornerRadius(20.0)
            }
            
            
        }
        .padding(.horizontal, 24.0)
        .navigationTitle("Create an Account")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2

Answers


  1. I had same issue where I could build the projects in simulator/real device without any problem but I couldn’t utilize the SwiftUI preview features.

    I had identical error message "Message send failure" where diagnostic report mentioned that they were not able to find relevant SwiftUI view files. I have raised a request to Apple for review.

    In the meantime, I have found a workaround by turning off "Automatically Refresh Canvas" option at

    Xcode >> Editor >> Canvas >> Automatically Refresh Canvas.

    This allowed preview to, at least load, and you can manually refresh them by using the play button in the device.

    enter image description here

    After turning it off, it would load preview and you can click on play button to refresh the preview.

    –Update on 12th Jan 2022–

    Spent a lot of time working on this issue and found a repeatable workaround, after receiving an email from AppleDTS that they think it’s a bug. Further request need to be made via feedback assistant and will share feedback from Apple, if I find anything useful.

    On my end, the issue popped up again time to time and found a (rather dirty) way to utilize SwiftUI if you are using M1 Macbook Pro and excluding Arm64 architecture in builds, along with various cocoapods. Below is the safest/fool-proof way I found so far, at least on my end, to get previews working.

    1. Clean Xcode (Derived Data, Device Support, Build Cache)
    2. (If you have cocoapods and XCworkspace file) arch -x86_64 pod deintegrate in terminal
    3. Remove old XCworkspace file and Podfile.lock
    4. Re-install pods – arch -x86_64 pod install
    5. Check "Open With Rosetta" in Xcode Info
    6. Open the new XCworkspace file
    7. Run iOS Simulator to build cache for iPhone (if there is iOS app)
    8. Run WatchOS Simulator to build cache for watch (if there is watchOS app)
    9. Ensure there are no further issues with cocoapods/swift version, etc at this point.
    10. Turn off "Automatically Refresh Canvas" to check if the preview loads, and also see "Message Send Failure" error message when Automatic canvas refresh function is turned ON (upon any changes made to contentView/SwiftUIview).
    11. Close the Xcode file, without removing build Cache.
    12. Uncheck "Open With Rosetta" in Xcode Info.
    13. Reopen XCworkspace file.
    14. (Optional) Run simulators
    15. Use SwiftUI while keeping the "Automatically Refresh Canvas" turned on.

    Do feel free to share if you have found a better solution in the meantime.This SO post was the one that lead me to the temporary workaround.

    “Cannot preview in this file – Connection interrupted: send previewInstances message to agent" error in Xcode 12

    Login or Signup to reply.
  2. As of October 2022, I tried the above, and it did not work for me. I kept messing with it and eventually my Xcode went into an infinite loading situation every time I opened the project.

    Luckily, all my recent changes were backed up to git. So I created a new folder outside of iCloud Drive, pulled the project, and everything — including previews — seem to be working now.

    Note: I do have "Open With Rosetta" on for Xcode

    Decided to try cloning outside of iCloud Drive thanks to this post: https://stackoverflow.com/a/73035814

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search