I'm getting a fatal error in a preview:
fatalError in Environment+Objects.swift at line 34.
Anyone any idea how to find this file
Xcode Previews
RSS for tagCreate an app UI and configure almost everything your users see using Xcode Previews.
Posts under Xcode Previews tag
127 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Just learning Swift and SwiftUI, having fun in Xcode. I have the following custom view defined, but when I try to test it, the information doesn't get updated as I expect. When I use the button defined INSIDE the custom view, the update works as expected. When I use the button defined in the Preview body, it doesn't. The "lines" variable of the custom view appears not to be updated in that case.
I know I'm missing something fundamental here about either view state binding or the preview environment, but I'm stumped. Any ideas?
import SwiftUI
struct ConsoleView: View {
var maxLines : Int = 26
private enum someIDs { case textID}
@State private var numLines : Int = 0
@State var lines = "a\nb\nc\n"
var body: some View {
VStack(alignment: .leading, spacing:0 ) {
ScrollViewReader { proxy in
ScrollView {
Button("Scroll to Bottom") {
withAnimation {
proxy.scrollTo(someIDs.textID, anchor: .bottom)
}
}
Text(lines)
.id(someIDs.textID)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .bottomLeading)
.padding()
.onChange ( of: lines) {
withAnimation {
proxy.scrollTo( someIDs.textID, anchor: .bottom)
}
}
}
Button("Add more") {
writeln("More")
//writeln(response)
}
}
}
}
private func clipIfNeeded () {
if (numLines>=maxLines) {
if let i = lines.firstIndex(of: "\n") {
lines = String(lines.suffix( from: lines.index(after:i)))
}
}
}
func writeln ( _ newText : String) {
print("adding '\(newText)' to lines")
//clipIfNeeded()
write( newText )
write("\n")
numLines += 1
print(lines)
}
func write ( _ newText : String) {
lines += newText
}
}
#Preview {
VStack() {
var myConsole = ConsoleView(lines: "x\ny\nz\n")
myConsole
Button("Add stuff") {
myConsole.writeln("Stuff")
}
}
}
Hi,
You're here because your project has issues related to Xcode Previews or Swift Previews. The issue you're experiencing may be the result of any of the following:
An error in your SwiftUI app, Xcode previews, or on-device previews.
A configuration error in your Xcode project, including any third-party dependencies or packages.
A system issue in the operating system, SwiftUI, or in Xcode Previews.
Based on your request, I need more information about your SwiftUI app when rendering Xcode Previews or on-device previews. Specifically, I’ll need the diagnostics Swift Previews generates to make sure I understand the error encountered by the preview system. Please create a report in Feedback Assistant to share the details requested in the instructions below.
For issues with macOS, Mac Catalyst, on-device iOS, or on-device visionOS previews, perform the following steps to gather diagnostics:
Download and install the Swift Previews logging profile for your device.
Reproduce the error while previewing on device, taking note of the timestamp when the error occurred.
Attach the Previews diagnostics, sysdiagnose from your Mac, a sysdiagnose from the previewing iOS or visionOS device.
For issues with Xcode Previews, perform the following steps to gather diagnostics:
Download and install the Swift Previews logging profile for your device.
Reproduce the error in Xcode Previews, if you haven’t already done so.
If an error banner appears in the canvas, click the "Diagnostics" button within the banner, then go to Step 5; otherwise, continue to Step 4.
If the error banner is missing, navigate to the menu in Xcode: Editor > Canvas > Diagnostics
In the presented sheet, click the "Generate Report" button.
Attach a zip file containing the diagnostic report to your bug report (it will be named something like previews-diagnostics-0123456789.zip).
Submitting your feedback
Before you submit to Feedback Assistant, please confirm the following information is included in your feedback:
with the Swift Previews logging profile installed, attach the sysdiagnose logs gathered after reproducing the issue
the Previews diagnostics generated by Xcode
timestamp identifying when the issue was reproduced
focused sample Xcode project that reproduces the issue (if applicable)
screenshots or videos of the error (optional)
Please include all requested information to prevent delays in my investigation.
After your submission to Feedback Assistant is complete, please respond to your original Forums post with the Feedback ID. Once received, I can begin my investigation and determine if this issue is caused by an error within your SwiftUI app, a configuration issue within your Xcode project, or an underlying issue in the operating system, SwiftUI, in Xcode Previews, or on-device previews.
Cheers,
Paris X Pinkney | WWDR | DTS Engineer
Trying to use SwiftUI Preview in Xcode 16.2 on complex project, I have no access to Developer Apple team, instead I am using manually installed provision profiles to test on iPhone.
So, SwiftUI Preview does not work with diagnostic error "Failure: Framework Agent preparation failed: Could not find a team ID"
how to fix swift preview on real device no showing
Question:
I have created a workspace containing a SwiftUI app and two frameworks:
B Framework: Handles UI components
C Framework: Handles service classes
I added a Podfile to manage dependencies. My Podfile is structured as follows:
inhibit_all_warnings!
workspace 'ABC.xcworkspace'
def shared_pods
# Shared pods here
pod 'Alamofire'
end
target 'A' do
use_frameworks!
project 'A/A.xcodeproj'
shared_pods
end
target 'B' do
use_frameworks!
project 'B/B.xcodeproj'
shared_pods
end
target 'C' do
use_frameworks!
project 'C/C.xcodeproj'
shared_pods
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
end
end
end
After installing pods and building the project, everything works fine except for Xcode’s SwiftUI Preview, which crashes with the following error:
xcpreviewagent crashed because Alamofire.framework is missing
Question:
How can I resolve this issue and make SwiftUI Previews work without Xcode crashing?
Hey,
I wanted to create a Mac-OS application. Normally I only code iPhone apps. But as soon as I want to display anything on the preview, it loads, just as normal, and then the throbber/progress indicator disappears and the preview canvas stays gray like it used to be before. I also don't get any error messages. Only one time after trying different things I got one message saying: "Could not launch Preview Shell." and "Could not create FBSOpenApplicationService." I also searched for a few solutions and tried some but none of them seemed to work. In the DiagnosticReports were some files of the time but I didn't seem to find anything helpful in there and they don't appear when I reopen my project or switch from PreviewMode "My Mac" to "iPhone 16 Pro".
When I launch the app on a simulator it works perfectly fine but this is quite annoying.
Thanks for trying to help me!
Hello,
I am currently encountering an issue where SwiftUI View Previews cannot be displayed when the View is defined in a Static Framework target. This issue only occurs under specific conditions.
Environment
Xcode: 16.2
Scheme Structure:
MainApp
Test Target: TestHogeFeature
Test Setting:
Gather coverage (Code coverage collection) enabled(all)
Target Structure:
MainApp (Application target)
Dependencies: [HogeFeature, Core]
HogeFeature (Static Framework target)
Dependencies: [Core]
Core (Framework target)
Dependencies: None
TestHogeFeature (Unit test target)
Dependencies: [HogeFeature]
Summary
I am currently working on a SwiftUI-based project and have encountered an issue where Previews fail to display under specific conditions. Below are the details:
Issue
In the MainApp scheme, when the code coverage collection setting (Gather coverage for) is enabled, Previews for SwiftUI Views within the HogeFeature (Static Framework) target fail to display correctly. However, the issue is resolved by taking one of the following actions:
Change HogeFeature from a Static Framework to a Dynamic Framework.
Remove the build setting MACH_O_TYPE: staticlib
Disable the Gather coverage setting in the MainApp scheme.
I have attached the actual error log from the failed Preview.
preview error log
Questions
Why does this issue occur only when using a Static Framework with code coverage enabled?
Is there any way to resolve this issue while maintaining the current configuration (Static Framework with code coverage enabled)?
I would appreciate any advice or insights regarding the cause and potential solutions.
Why are asynchronous tasks not executed in Xcode Canvas, and why do they only work in the simulator?
Hi everyone, I'm new to Xcode and iOS development. I've encountered an issue where asynchronous tasks seem to not execute in Xcode Canvas, but they work fine in the simulator. Can anyone explain why this might be happening or what I could do to fix it? Thank you for your help!
struct PartnerProfileView: View {
@State private var showSheet: Bool = true
let partnerName: String
var body: some View {
ZStack(alignment: .bottom) {
Color("EFEFF4_0F2534")
ScrollView(showsIndicators: false) {
headerSection()
infoSection()
.padding(.bottom, 5)
sectionTitle("Other Skills")
skillsGrid()
sectionTitle("···")
dynamicsSection()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
CustomTabBar()
}
.navigationBarHidden(true)
.ignoresSafeArea(edges: .all)
.onAppear {
print("PartnerProfileView received")
Task {
await BottomCustomPopup().present()
}
}
.onChange(of: showSheet) { oldState, newValue in
print("oldState \(oldState)")
print("newValue \(newValue)")
}
}
}
//@MainActor
struct BottomCustomPopup: BottomPopup {
var body: some View {
HStack(spacing: 0) {
Text("Hello World")
Spacer()
Button(action: { Task { await dismissLastPopup() }}) { Text("Dismiss") }
}
.padding(.vertical, 20)
.padding(.leading, 24)
.padding(.trailing, 16)
}
}
I have a dummy project that is set up in the following way:
one Xcode project
two frameworks, UI and Feature, Feature embeds UI-framework
three app targets, two that are SwiftUI lifecycle and one UIKit lifecycle
all app targets import the Feature framework
all app targets have same setup for asset catalogue
The point of this setup is to be able to switch between app target scheme and see preview changes accordingly. That works 100% with anything coming from the asset catalogue and even localization catalogues.
The dummy project exists as a proof of concept for the main project (8 years old, all Swift) I am working on. However, the same setup does not work in the main project.
I am suspecting it has to do with how the project is initialised and bundles. I print out the bundles to see which bundles are registered.
Dummy project will print out the bundle based on app target, the main bundle being based on the selected scheme.
The main project will have the previews.com.apple.PreviewAgent.iOS as main bundle.
I am not able to use SwiftUI Preview
Here is the report I get while trying to see the issue:
Here is the report of the issue:
And here is the call and code preview:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
}
}
#Preview {
ContentView()
}
Please update.
Hi,
I want to run the live preview on my iPhone, but I received the error message that the app failed to launch.
How can I fix this? Everything is made with SwiftUI
Thanks
class ViewModel : NSObject, ObservableObject, ASWebAuthenticationPresentationContextProviding {
private var authSession: ASWebAuthenticationSession?
func signInWithOpenID(provider: OAuthProvider) {
let url = getOIDCAuthenticationURL(provider: provider)
authSession?.cancel()
authSession = nil
authSession = ASWebAuthenticationSession(url: url, callbackURLScheme: "com.ninjanutri") { callbackURL, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let callbackURL = callbackURL else { return }
guard let idToken = callbackURL.valueOf("id_token") else { return }
self.signInWithIdToken(provider: provider, idToken: idToken)
}
authSession?.prefersEphemeralWebBrowserSession = false
authSession?.presentationContextProvider = self
authSession?.start()
}
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return ASPresentationAnchor()
}
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
Button {
viewModel.signInWithOpenID(provider: .github)
} label: {
Text("Test")
}
}
}
when the prefersEphemeralWebBrowserSession is false, the alert and webview is totally working fine in Simulator and Real device, but not XCode Preview. Is this behaviour expected or it's a bug?
I recieve the error message "XOJITError: Could not create code file directory for session: Permission denied". I'm Using Xcode 16.2.
It is an AppKit project using SwiftUI and it also happens if I create a clean project.
Error log is attached.
previews_diagnostics_summary.txt
Hello everyone, I've encountered an issue with SwiftUI Preview and would appreciate your help.
Problem Description In a mixed Objective-C and Swift project, I'm experiencing the following situation with SwiftUI Preview:
Crashes when previewing on a physical device
The same code runs normally when launched directly through Xcode
Project uses CocoaPods for dependency management with static frameworks
Project Environment:
Project Type: Mixed (Objective-C + Swift)
Dependency Management: CocoaPods
Dependency Type: Static frameworks
Device: Physical device preview
Steps to Reproduce:
Write Preview code in SwiftUI file
Select physical device as Preview device
Click Preview button
Application crashes
When working on my Xcode project and using Previews from time to time I find preview crashes and ens up with the image below. The UI is completely unresponsive and only way to bring it back I find is close and relaunch Xcode.
Anyone else experience this - is there a known fix or a better way to "kick" preview to restart that doesn't involve full relaunch of XCode
Hi there, i just want to know, why my xcode is not showing any print in my Xcode, when i build it, it tell me "Ready to continue xx" but the result of my code doesnt appear in right panel
My preview crashed because it could not access my font resources. I am working on a Framework, and it seems that for frameworks, the resources are not copied into the app package of the preview.
Investigation:
I verified this by examining the contents of the preview: /Users/YOUR_NAME/Library/Developer/Xcode/UserData/Previews/Simulator Devices/DEVICE_UUID/data/Containers/Bundle/Application/APPLICATION_UUID/APPLICATION_NAME.app
Make sure to replace "YOUR_NAME," "DEVICE_UUID," "APPLICATION_UUID," and "APPLICATION_NAME" with the actual names or UUIDs relevant to your specific situation.
Now right-click on the app and select Show Package Contents.
For previews that work correctly, the name of the associated app is used, and you will see all the resources in the package.
However, my framework was not using the framework name. Instead, it was named XCPreviewAgent.app and did not contain any resources from my framework.
Fix:
As of November 2024 (Xcode 16.0 and Xcode 16.1), the fix is to use Legacy Preview Execution.
In the menu, select Editor > Canvas > Legacy Preview Execution.
Please leave a comment if this is fixed in a newer Xcode version.
I got a preview crash info as this:
*** crashed due to fatalError in PersistentModel.swift at line 559.
This KeyPath does not appear to relate RecordInfo to anything - \RecordInfo.<computed 0x00000001921dfb4e (Array<SomeInfo>)>
If I change preview device to iPhoneSE, It is no crash.
I think the reason is I have some dirty data in iPhone16 Pro preview device.
If I'm right and how to delete it?
Model of RecordInfo like this:
@Model
class RecordInfo {
@Relationship(deleteRule: .cascade) var someInfo:[SomeInfo]
}
@Model
class SomeInfo {
var date: Date
var info: String
}
Views can be viewed on the canvas in XCode via the code below.
#Preview {
ContentView()
}
But how do I preview an App class in XCode?
Background: I'd like to preview various settings done in the Scene of the App.