Up until now, it was possible to check in build scripts via the ENABLE_PREVIEWS environment variable whether a build for a SwiftUI preview is being executed.
In addition, it was also possible to conditionally compile code for SwiftUI or exclude it from compilation using this variable.
This no longer works with Xcode 16 and the new SwiftUI Preview compilation!
There is still the option to switch to the old system with the "Use Legacy Previews Execution" setting, but as stated in the release notes, this option will be removed at some point.
Which brings us back to the old problem of not being able to exclude build scripts from preview builds and not being able to prevent certain code from being compiled / add special code for SwiftUI previews.
This is a terrible situation, especially for more complex projects in which precisely the points mentioned are important for the build process.
I seriously hope Apple provides us with another environment variable for SwiftUI preview builds that we can use.
Xcode Previews
RSS for tagCreate an app UI and configure almost everything your users see using Xcode Previews.
Posts under Xcode Previews tag
139 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
When I attempt to preview my code, I encounter an error message stating, “Cannot preview in this file: Failed to launch (App Name).” This issue is specific to this particular app. I attempted creating a new project, and that works fine.
This is what it says in the diagnostics:
| [Remote] JITError
|
| ==================================
|
| | [Remote] LLVMError
| |
| | LLVMError: LLVMError(description: "The file was not recognized as a valid object file")
Hello... for some reason, XCode previews are no longer working for me. It was working fine a week ago, however, now no matter ho many times i reboot or restart my computer, the preview won't load. The preview is stuck on "loading Preview" no matter how long I wait. I ran the same files on swift playgrounds and the preview works fine there, but not on XCode.
I ran both my project and a completely new, unedited project and both will not preview- so I know it is not a problem with my file. Also, the second I open the app the preview pauses. Either way, I don't think an app with only one file should take so long to build...
Hello,
I have a simple SwiftUI view that shows this bottom bar in the view and
I noticed that in SwiftUI previews the 2D window is squared off while in the simulator it has rounded edges. This effects the bottom bar because as you can see in the simulator the text is cut off. I am using Xcode 16 beta and visionOS 2 beta.
Why do the two windows look different? And I am surprised the text is getting cut off in the rounded window.
SwiftUI Preview:
Vision Pro Simulator
for sometime, preview is "collapsed", see attached snapshot
I have SwiftUI views, which access the user defaults by using the property wrapper @AppStorage.
Now I would like to have a preview with multiple variations of the view depending on the same user default with different values.
Is there a pure way to do that?
Currently I have a solution which is very probably a hack and supports only one variation of the user default. To do that I define the user settings in a sub views onAppear() method:
struct MyTestedView_Previews : PreviewProvider {
static var previews: some View {
VStack
{
VStack
{
MyTestedView
.previewLayout(.sizeThatFits)
}
.onAppear{
UserDefaults.standard.set(true, forKey: "myConsumedKey")
}
//VStack
//{
// MyTestedView
// .previewLayout(.sizeThatFits)
//}
//.onAppear{
// UserDefaults.standard.set(false, forKey: "myConsumedKey")
//}
}
}
}
When I have two VStack for different variations and I set the user defaults to different values in their onAppear(), only one user default value wins and I see one variation of my view twice.
What I also don't like on my solution, is that I don't know where this user default is stored. Is it stored temporary in the memory or do I even manipulate Xcode's user defaults?
Does anybody know if SwiftUI has already a solution to test different variations of user defaults in the preview?
I wanted to experiment a little using UINavigationController with SwiftUI App Lifecycle
I created a Custom Navigation Controller named JDNavigationController. It does not do much other than having the @Observable macro
public struct NavigationControllerStack<Content: View>: UIViewControllerRepresentable {
private let initialView: () -> Content
@State private var controller = JDNavigationController()
public init(content: @escaping () -> Content) {
self.initialView = content
}
public func makeUIViewController(context: Context) -> JDNavigationController {
let viewController = self.initialView()
.environment(self.controller)
.viewController
self.controller.viewControllers = [
viewController
]
return controller
}
public func updateUIViewController(_ uiViewController: JDNavigationController, context: Context) {
}
public typealias UIViewControllerType = JDNavigationController
}
when I check, the functionality of the navigation controller works as expected, however, I can't for the life of me to change the background color of the status bar.
#Preview {
NavigationControllerStack {
ZStack {
Color.purple
.ignoresSafeArea(.all)
VStack {
Text("somethign")
}
}
}
}
I have tried
Using the appearance functions
Creating a Custom View Controller, and in that view controller I tried using a Hosting Controller by adding the hosting controller as a child and
setting hostingController.view.insetsLayoutMarginsFromSafeArea = false
using the toolbar modifiers from SwiftUI View
none seems to work.
I opened the View Debugger it looks like the white portion comes from the UIHosting Controller but I am not sure what I can do to fix it
This can be easily reproduced in a vanilla Xcode 16 beta 3 project.
Steps
Create a new project.
By default, previews work fine because default SWIFT_COMPILATION_MODE is Incremental. (aka Batch Mode)
Now, change it to WMO, and notice the previews crash with the enclosed crash report.
Feedback filed with reproducer + diagnostics + crash report:
https://feedbackassistant.apple.com/feedback/14268698
We have observed that enabling Whole Module Optimization (WMO) improves build times in our project. Therefore, if Previews can be compatible with WMO, it would be highly beneficial. Otherwise, it would be helpful to provide a warning or feedback to developers, as many projects are likely utilizing WMO, and identifying issues solely from crash reports can be challenging.
Note: This works all fine with the Legacy Previews Engine in Xcode 15/16.
We have been seeing a dyld loader crash when trying out the new Previews engine in Xcode 16 beta 3.
Feedback filed with reproducer + diagnostics: https://feedbackassistant.apple.com/feedback/14323960
Investigation:
Running nm -a on the debug dylib reveals duplicate SO entries pointing to SomeStatic.swift. One entry originates from the LibAStatic module, while the other comes from the LibBStatic module.
Local workaround - 1 Providing unique file names resolves the issue. However, these files are in different modules, so ideally, this shouldn't be necessary. Our codebase is extensive, and many code-generated modules have the same file names. Therefore, renaming files to ensure uniqueness is not a simple solution for us due to various complexities.
Local workaround - 2 Making these dependencies dylibs instead of static libraries also resolves the issue. However, we can't pursue this direction because a significant portion of our pre-build setup, foundations, and vendor linkages are statically linked.
Note: The same flow works with "Legacy Preview Engine in Xcode 16/15" but dynamic replacement has other issues, which we are super happy that the new engine doesn't make use of.
This issue is currently a blocker for us in trying out the new Previews in our project, it would be highly beneficial if this problem could be resolved soon.
I have just installed Xcode and the simulator is not working correctly I get the following error
"Cannot preview in this file Unexpected error occurred"
I have a multi-platform app with the SwiftUI code a separate Swift Package. Any Views with SwiftUI Previews break the compilation of the app. Here's the error message I get in Xcode:
Showing All Messages
ld: warning: Could not parse or use implicit file '/Applications/Xcode-beta.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it
Undefined symbols for architecture arm64_32:
"(extension in SwiftUI):DeveloperToolsSupport.Preview.init(_: Swift.String?, traits: DeveloperToolsSupport.PreviewTrait<DeveloperToolsSupport.Preview.ViewTraits>..., body: @Swift.MainActor @Sendable () -> SwiftUI.View) -> DeveloperToolsSupport.Preview", referenced from:
static BitnessViews.$s12BitnessViews33_ABDBADF565C741E50A2A5746CE94FCD9Ll7PreviewfMf_15PreviewRegistryfMu_.makePreview() throws -> DeveloperToolsSupport.Preview in BitnessViews.o
ld: symbol(s) not found for architecture arm64_32
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Could not parse or use implicit file '/Applications/Xcode-beta.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it
Undefined symbol: (extension in SwiftUI):DeveloperToolsSupport.Preview.init(_: Swift.String?, traits: DeveloperToolsSupport.PreviewTrait<DeveloperToolsSupport.Preview.ViewTraits>..., body: @Swift.MainActor @Sendable () -> SwiftUI.View) -> DeveloperToolsSupport.Preview
Linker command failed with exit code 1 (use -v to see invocation)
Any thoughts as to what might be going on here?
Hello,
I‘ve started developing an App not to long ago on Xcode and I have noticed that I can’t see any progress or like preview of what I have coded so far and it’s starting to concern me. I have Xcode version 15.5 and I am coding with swift, everything works fine there is no error or anything preventing it to run but when I try to preview the only thing I see when I launch the Simulator and I open my app the only thing I see is a white page.
Can someone please help me.
The SwiftUI previews have been working fine in Xcode 16.0 beta, but ever since I added Firebase into my app, I've been getting error with previews.
CrashReportError: IshaanCord crashed
IshaanCord crashed. Check ~/Library/Logs/DiagnosticReports for crash logs from your application.
Process: IshaanCord[5651]
Date/Time: 2024-07-04 19:29:51 +0000
Log File: <none>
"Cannot preview in this file"
Does anyone know how to fix this? Thank you.
I wanted to get my SwiftData previews working in my primary project, so I started modeling them after the SampleTrips project.
After messing around with that & being unable to make it work, I brought the same (working) sample code into my main project, unfortunately that's not working...
I've attached the preview error (note, there's nothing in the Diagnostic Reports).
//Sample code that works in it's own project, but not my primary target.
import SwiftUI
import SwiftData
struct TestSwiftDataStuffView: View {
let trip: Trip
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, \(trip.name)!")
.padding()
.foregroundColor(.red)
}
.padding()
}
}
#Preview(traits: .sampleDataSecondary) {
@Previewable @Query var trips: [Trip]
TestSwiftDataStuffView(trip: trips.first!)
}
actor DataModelSecondary {
struct TransactionAuthor {
static let widget = "widget"
}
static let shared = DataModelSecondary()
private init() {}
nonisolated lazy var modelContainer: ModelContainer = {
let modelContainer: ModelContainer
let schema = Schema([
Trip.self
])
do {
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .none)
modelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Failed to create the model container: \(error)")
}
return modelContainer
}()
}
@Model class Trip {
@Attribute(.preserveValueOnDeletion)
var name: String
init(name: String) {
self.name = name
}
}
extension Trip {
static var previewTrips: [Trip] {
[
Trip(name: "Revenant"),
Trip(name: "Newcastle"),
Trip(name: "Bianca")
]
}
}
struct SampleDataSecondary: PreviewModifier {
static func makeSharedContext() throws -> ModelContainer {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: Trip.self,
configurations: config
)
SampleDataSecondary.createSampleData(into: container.mainContext)
return container
}
func body(content: Content, context: ModelContainer) -> some View {
content.modelContainer(context)
}
static func createSampleData(into modelContext: ModelContext) {
Task { @MainActor in
let sampleDataTrips: [Trip] = Trip.previewTrips
let sampleData: [any PersistentModel] = sampleDataTrips //+ sampleDataLA + sampleDataBLT
sampleData.forEach {
modelContext.insert($0)
}
try? modelContext.save()
}
}
}
@available(iOS 18.0, *)
extension PreviewTrait where T == Preview.ViewTraits {
@MainActor static var sampleDataSecondary: Self = .modifier(SampleDataSecondary())
}
Xcode16Preview.txt
Basically, in my widget/live activity, I want to extract reusable views into a separate file with an isolated view and preview. Dummy example below.
I cannot do it because it says "missing previewcontext".
The only way I've found is to add the view to my main app target, but I don't want to clutter my main app wiews that only exist in my widgets if I can avoid it.
Can this be done somehow? Thoughts appreciated.
Dummy example (tried with and without "previewLayout":
struct StatusActivityView: View {
let status: UserStatusData
var body: some View {
VStack(alignment: .center) {
Text("Dummy example")
}.background(.blue).padding(5)
}
}
@available(iOS 16.2, *)
struct StatusActivityView_Previews: PreviewProvider {
static var previews: some View {
let status = WidgetConstants.defaultEntry()
return StatusActivityView(status: status).previewLayout(.sizeThatFits)
}
}
Hello,
Today earlier I changed my macOS user account name and now I'm getting error at Xcode 16 at Preview.
A piece of error report is:
XOJITError: Could not create oop-jit code file directory /Users/victorvaz/Library/Developer/Xcode/UserData/Previews/Simulator Devices/CCCD8E24-3E82-4B02-9D30-0E2B5D09EB4A/data/Containers/Data/Application/D4EA132D-A318-4D58-8618-DFD428FD5F71/tmp/OOPJit/previews: Permission denied
But "victorvaz" is my old macOS user account name, how can I make Xcode identify my new account name?
Kind regards,
Victor de Oliveira
I have been trying to get a preview to load for hours and it won't get passed the 'Preparing iPhone Simulator for Previews' and it has been days and nothing works. I've tried almost everything. I really need this to work, but it hasn't worked for weeks at this point.
Cannot select individual view in selectable mode in Xcode preview, it only show the whole blue device border.
I don't know why after I connected to firebase in my app my preview just started to crash. here are some screen shots
== PREVIEW UPDATE ERROR:
JITError
==================================
| NoBuiltTargetDescriptionCouldBeFound
|
| translationUnit: PreviewTranslationUnit(moduleNamePrefix: "Previews_EmptyFeedRow", sourceIdentifier: file:///Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift -> EmptyFeedRow.swift, parseTree: ParseTree(version: 727, statements: 3, providers: 1), update: nil, changesContextMemoizer: PreviewsPipeline.PreviewTranslationUnit.(unknown context at $34b4b9c4c).ChangesContextMemoizer(parseTree: ParseTree(version: 727, statements: 3, providers: 1), sourceIdentifier: file:///Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift -> EmptyFeedRow.swift, cachedValue: os.OSAllocatedUnfairLock<Swift.Optional<PreviewsModel.ParseTree.PreviewChangesContext>>(__lock: Swift.ManagedBuffer<Swift.Optional<PreviewsModel.ParseTree.PreviewChangesContext>, __C.os_unfair_lock_s>)), registryDeclarationMemoizer: PreviewsPipeline.PreviewTranslationUnit.(unknown context at $34b4b9bec).RegistryDeclarationMemoizer)
|
| builtTargetDescriptions:
|
== VERSION INFO:
Tools: 16A5171c
OS: 24A5264n
PID: 906
Model: MacBook Pro
Arch: arm64e
== ENVIRONMENT:
openFiles = [
/Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift
]
wantsNewBuildSystem = true
newBuildSystemAvailable = true
activeScheme = JournalApp
activeRunDestination = iPhone 15 Pro variant iphonesimulator arm64
workspaceArena = [x]
buildArena = [x]
buildableEntries = [
Remember.app
]
runMode = JIT Executor
== SELECTED RUN DESTINATION:
name = iPhone 15 Pro
eligible = true
sdk = Optional(<DVTSDK:0x13870da30:'iphonesimulator18.0':Simulator - iOS 18.0:<DVTFilePath:0x600001e8c700:'/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator18.0.sdk'>>)
variant = Optional("iphonesimulator")
device = Optional(<DVTiPhoneSimulator: 0x32f00d290> {
SimDevice: iPhone 15 Pro (CF3C85BC-F559-4437-9072-7F30153B399B, iOS 18.0, Booted)
PairedSim: <DVTiPhoneSimulator: 0x33733d150> {
SimDevice: Apple Watch Series 9 (45mm) (627CE93E-EB02-4200-BE40-3DCB5C91DB44, watchOS 11.0, Shutdown)
}
})
== SELECTED RUN DESTINATION:
Simulator - iOS 18.0 | iphonesimulator | arm64 | iPhone 15 Pro | Apple Watch Series 9 (45mm)
jit enabled: true
fallback to dynamic replacement: false