for sometime, preview is "collapsed", see attached snapshot
Xcode Previews
RSS for tagCreate an app UI and configure almost everything your users see using Xcode Previews.
Posts under Xcode Previews tag
153 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
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
To reproduce:
In Xcode, create a new project with SwiftData storage
Add a new item in the preview — everything works fine so far
Enable CloudKit sync for the target (add iCloud capability, check CloudKit, add a container)
Go back to the preview and add a new item — Xcode will now freeze
As soon as you modify the SwiftData storage, the preview freezes and the Xcode app becomes extremely slow until you either refresh the preview or restart Xcode.
Hi, i am currently updating my app in SwiftUI from iOS 16.4 to 18.0, i am getting in xcode these new warning
@State' used inline will not work unless tagged with '@Previewable'
so i fix the problem with the suggestions and add the new tag @Previewable and put the variable in the first line of the preview
#Preview {
@Previewable @State var enabled: Bool = true
return NotificationLabel(enabled: $enabled, type: "test", icon: "star", title: "test", description: "test")
}
the problem is that my app is available from iOS 16.4 to iOS 18.0 and the preview gives me this error
'Previewable()' is only available in iOS 18.0 or newer
but if i put a versione if at the top i get another error
if #available(iOS 18.0, *){
@Previewable @State var enabled: Bool = true
@Previewable' items must be at root scope in the preview block
is there a way to silence the warning making a two version preview, one for iOS 18 and one for the previous versions?
Crowdstrike Falcon vs Xcode performance
Our IT department is using CrowdStrike Falcon, an ML-security tool, on all the Mac hardware. It will flag processes as malicious, and it sounds like it may sandbox such processes that are deemed malicious and / or scan anything the process touches.
TLDR
Does anybody know how to make CrowdStrike Falcon behave nicely with Xcode and its tools and prevent it from consuming high CPU and interfering with the build and debugging processes? Xcode, SwiftUI previews and building should be as performant as possible.
Details
Perplexity describes CrowdStrike Falcon as follows:
CrowdStrike Falcon is a cloud-based endpoint security platform that provides real-time protection against malware, ransomware, and other cyber threats. It uses artificial intelligence and machine learning to detect and prevent known and unknown threats across endpoints (laptops, desktops, servers, etc.), cloud workloads, and cloud environments. The Falcon platform includes next-generation antivirus, endpoint detection and response (EDR), managed threat hunting, vulnerability management, and other security capabilities delivered through a lightweight sensor that streams data to the CrowdStrike cloud for analysis and response.
The problem is that apparently Falcon's ML signatures will flag Xcode as malicious. So when building in Xcode, Falcon will use a huge amount of CPU (I have seen it go up to 456%), affecting build performance. I am getting the impression it is sandboxing and / or scanning every single file Xcode touches. The same goes for the iOS Simulator which will also cause Falcon to consume lots of CPU. It's clear this is affecting our build performance a lot.
Falcon supports a number of exclusions:
Machine learning (ML) exclusion: For trusted file paths, stop all ML-based detections and preventions, or stop files from being uploaded to the CrowdStrike cloud.
Indicator of attack (IOA) exclusion: Stop all behavioral detections and preventions for an IOA that’s based on a CrowdStrike-generated detection.
Sensor visibility exclusion: For trusted file paths that you want to exclude from sensor monitoring, minimize sensor event collection, and stop all associated detections and preventions. Use sensor visibility exclusions with extreme caution. Potential attacks and malware associated with excluded files will not be recorded, detected, or prevented.
Using Sensor Visibility Exclusions it is possible to exclude applications on file pattern basis and preventing Falcon's ML signatures for flagging any such process as malicious. Which means that it is possible to exclude /Applications/Xcode.app/** and prevent it, or the processes it spawns, as malicious.
However, Xcode and the toolchain are much more complicated than just excluding a single binary. Switching toolchains via sudo xcode-select -s will also update a lot of files in /usr (see Xcode.app/Contents/Developer/usr) such as /usr/bin/swift*, /usr/bin/ibtool*, /usr/bin/lldb and /usr/bin/xcrun (there are many more).
For testing Xcode performance we excluded /Applications/Xcode.app/** and /usr/bin from Falcon, but just launching the simulator and a simulator build of the app will still cause Falcon to go up to about 300%. I assume this will affect SwiftUI live previews as well. Probably /Users/*/Library/Developer/** should be excluded as well then?
Obviously, Falcon's AI/ML should just identify all of this as legitimate software development tools and no exclusions should be necessary...
IMHO a file-pattern based exclusion seems to contradict what this tool is supposed to do. I would think it should evaluate signing (codesign / spctl) or validate checksums, rather than file pattern based exclusions. But as long as Xcode becomes more performant I am not complaining. The less an IT tool is flagging legitimate software as malicious and interfering with our daily work, the better.
So my question is if anybody knows how to make CrowdStrike Falcon behave nicely with Xcode and its tools and prevent it from consuming high CPU and interfering with the build and debugging processes? Xcode, SwiftUI previews and building should be as performant as possible.
I have a project with two local packages
One client package with an interface and some models with dynamic type in the Package.Swift
One feature package with the UI and a dependency to the client package
When I try to preview a view that is not using any models or code from the client package, it loads just fine e.g. a view that is just a container to display things like a card
But when I tried to preview any other view that actually uses models from the client package, it just fails
the first few lines of the preview error display
LinkDylibError: Failed to build <filename>.swift
Linking failed: linker command failed with exit code 1 (use -v to see invocation)
ld: warning: search path '/Applications/Xcode-15.4.0.app/Contents/SharedFrameworks-iphonesimulator' not found
Undefined symbols for architecture arm64:
Also, I'm using Xcode 15.4 and iOS 17 as the min version