SwiftUI: Automatic Preview Updating Error "Failed to build ContentView.swift"

Viewed 18715

I'm trying to run the Automatic Preview in Xcode 11, however even though the project builds successfully, the automatic preview fails giving me the error Failed to build ContentView.swift. Failed to code sign ContentView.swift.

I have just created the project without any modifications to the auto generated code. Even the code signing has also been set properly. Note I'm using the Free Apple Developer Account. Could this cause any problem?

Following is the code from ContentView.swift file:

import SwiftUI

struct ContentView : View {
    var body: some View {
        Text("Hello World")
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
8 Answers

First select the Xcode using following command

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

Then run

sudo xcodebuild -license

Hope it is helpful

I solved that problem by going to the Xcode - Preferences -> Locations and assigning the Command Line Tools to Xcode 11. Also keep in mind that it is a beta, so it is unstable.

I had this problem as I was using // to comment beside my curly brackets to check I had them all in the right spot in my screen code. Xcode seems to cope with a few but once the screen gets too large and too many comments...... Now I comment on the line below and no problems!

Xcode SwiftUI Previews may occasionally fail with an error message about a modified .h file, such as “file Header.h has been modified since the module file Module.pcm was built: mtime changed.” (85938686)

Workaround: Delete the Clang module cache by running the following command in Terminal:

rm -rf "$TMPDIR/../C/clang/ModuleCache"

Then try to preview the file again.

https://developer.apple.com/documentation/Xcode-Release-Notes/xcode-13_3-release-notes

I had this problem too. I solved it by moving the file location of the file I was trying to preview. When the file was created it was down below the resources folder, so I moved it up and then preview worked.

I am currently having this problem with XCode 12.2, it says "Failed to build ContentView.swift." and when you click on the information's button it says "Extra tokens at end of #SourceLocation". Apparetly that was because i wrote a "// Comment" in the same line, next to a variable definition, so i solved this only moving the comment to the next line. I don't know who i can help this, but just wanted to share it. Regards!

Change your iOS version to the latest one. It will solve your issue. enter image description here

I encountered this problem too. I download Xcode beta-1 before I download macOS 10.15. Then after my system upgrade to 10.15, the preview function didn't work. It turns out that Apple has released Xcode beta-2 version recently, so I downloaded and it worked. So, KEEP THE NEWEST VERSION OF XCODE!!!!

Related