Xcode Previews

RSS for tag

Create an app UI and configure almost everything your users see using Xcode Previews.

Posts under Xcode Previews tag

125 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SortDescriptor from a generic method crashes Xcode Previews but not Simulator.
I attempted to create a SortDescriptor using a method in enum to sort various different models in SwiftUI lists. But it causes crashes in Xcodes previews but not in the simulator, and I don't know why. Maybe someone could suggest changes. extension Item:ListSorting {} //List sorting is a protocol given to various Models enum ListSortingStyle<T>:String,CaseIterable where T:ListSorting { case alphabetical = "A…Z" case alphabeticalReverse = "Z…A" case createDate = "Newest" case createDateReverse = "Oldest" case editDate = "Latest Edit" case editDateReverse = "Oldest Edit" /// Returns a SortDescriptor matching the enumeration func sortDescriptor() -> SortDescriptor<T> { switch self { case .alphabetical: SortDescriptor<T>(\.name, comparator: .localized, order: .forward) case .alphabeticalReverse: SortDescriptor<T>(\.name, comparator: .localized, order: .reverse) case .createDate: SortDescriptor<T>(\.creationDate, order: .forward) case .createDateReverse: SortDescriptor<T>(\.creationDate, order: .reverse) case .editDate: SortDescriptor<T>(\.editDate, order: .forward) case .editDateReverse: SortDescriptor<T>(\.editDate, order: .reverse) } } } Which is used in struct ItemsList: View { @Environment(\.modelContext) private var modelContext @Query private var items:[Item] = [] init(sortStyle:ListSortingStyle<Item> = .alphabetical) { let sortDescriptor = SortDescriptor<Item>(\.name, comparator: .localized, order: .forward) //(1) This works in preview & simulator //OR let sortDescriptor2 = sortStyle.sortDescriptor() //(2) This crashes in a preview when used in a fetch not in the iOS simulator print(sortDescriptor,sortDescriptor2) let descriptor = FetchDescriptor<Item>(sortBy:[sortDescriptor2]) self._items = Query(descriptor) } var body: some View { ... } } As far as I can see both methods create a SortDiscriptor. If I print the sortDescriptor variable in they look almost identical: //1 SortDescriptor<Item>( order: Foundation.SortOrder.forward, keyString: nil, comparison: Foundation.SortDescriptor<MyApp.Item>.AllowedComparison.comparableString( (extension in Foundation):Swift.String.StandardComparator(options: __C.NSStringCompareOptions(rawValue: 0), isLocalized: true, order: Foundation.SortOrder.forward), \Item. <computed 0x0000000340213b18 (String)>) ) //2 SortDescriptor<Item>( order: Foundation.SortOrder.forward, keyString: nil, comparison: Foundation.SortDescriptor<MyApp.Item>.AllowedComparison.comparableString( (extension in Foundation):Swift.String.StandardComparator(options: __C.NSStringCompareOptions(rawValue: 0), isLocalized: true, order: Foundation.SortOrder.forward), \Item.<computed 0x0000000340022174 (String)>) ) But the one created with the generic method on the enum crashes with the error message: CrashReportError: Fatal Error in DataUtilities.swift MyApp crashed due to fatalError in DataUtilities.swift at line 64. Couldn't find \Item.<computed 0x0000000340022174 (String)> on Item with fields [SwiftData.Schema.PropertyMetadata ...
2
0
25
3d
Failed to Install Preview App on iPhone in Xcode Previews (HelloWorldApp)
Hi everyone, I'm encountering an issue when trying to run Xcode Previews for my HelloWorldApp on a real iPhone device. The app fails to install, and I get the following error message: Development Environment: Xcode Version: 16C5032a macOS Version: 23H420 Test Device (iPhone): iPhone 12 mini, iOS 15.5 (19F77) MacBook: MacBook Air (M1, arm64e) Error Message: Whenever I attempt to preview the app using SwiftUI Previews on my iPhone (iPhone của Định), I get the following installation error: FailedToInstallAppError: Failed to install ”HelloWorldApp.app” Could not install the preview host ”HelloWorldApp.app” on iPhone của Định Here’s part of the detailed log: agentBundle = com.DihNgx.HelloWorldApp { url: file:///Users/dihngx/Library/Developer/Xcode/DerivedData/HelloWorldApp-eyeszqttvaydocbdmoiwcczlazrt/Build/Intermediates.noindex/Previews/iphoneos/HelloWorldApp/Products/Debug-iphoneos/HelloWorldApp.app signingInformation: Code Signing { identifier: com.DihNgx.HelloWorldApp identity: A9A830FA23874E2047C974D6621D441EB9CBC7CC hasGetTaskAllow: true isSandboxed: false } } Device Information: Device Name: iPhone của Định Device Identifier: 00008101-001C482922C0001E iOS Version: 15.5 Provisioning profile installed: "iOS Team Provisioning Profile: com.DihNgx.HelloWorldApp" Steps I’ve already tried (but the issue persists): Ensured that Xcode recognizes the iPhone and that the device is connected properly. Checked Code Signing and Provisioning Profile (no issues were shown). Cleaned the build folder (Cmd + Shift + K) and deleted Derived Data. I’d really appreciate any advice or suggestions on how to solve this issue. Has anyone else faced a similar error or knows how to fix this? Thanks so much in advance!
1
0
28
6d
SwiftUI Preview Fails to Load While Project Builds and Runs Fine: Alamofire Module Map Issue
I'm having an issue specifically with SwiftUI previews in my iOS project. The project builds and runs fine on devices and simulators (in Rosetta mode), but SwiftUI previews fail to load in both Rosetta and native arm64 simulator environments. The main error in the preview is related to the Alamofire dependency in my SiriKit Intents extension: Module map file '[DerivedData path]/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.modulemap' not found This error repeats for multiple Swift files within my SiriKit Intents extension. Additionally, I'm seeing: Cannot load underlying module for 'Alamofire Environment Xcode version: 16.2 macOS version: Sonoma 14.7 Swift version: 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1) Dependency management: CocoaPods Alamofire version: 5.8 My project is a large, older codebase that contains a mix of UIKit, Objective-C and Swift Architecture Issue: The project only builds successfully in Rosetta mode for simulators. SwiftUI previews are failing in both Rosetta and native arm64 environments. This suggests there may be a fundamental issue with how the preview system interacts with the project's architecture configuration. What I've Tried I've attempted several solutions without success: Cleaning the build folder (⇧⌘K and Option+⇧⌘K) Deleting derived data Reinstalling dependencies Restarting Xcode Removing and re-adding Alamofire
1
0
37
6d
Question about using @Previewable
This is an issue that occurred while using SwiftUI. Cannot find '$state' in scope The other view finds properties normally. May I know why the error is occurring? The following code is the full text of the code that causes problems. import SwiftUI @Observable class HomeState { var title: String = "Home" } struct HomeView: View { @Binding var state: HomeState var body: some View { Text(state.title) } } #Preview { @Previewable @State var state: HomeState = .init() HomeView(state: $state) /// Error: Cannot find '$state' in scope } The same error occurs when using the String type rather than the object. What did I do wrong?
2
1
183
2w
SwiftUI Preview Runtime linking failure
I'm using GoogleMaps in my project. Legacy preview works well but new preview (Xcode 16.3.1 beta) produces error. It doesn't seem to find Googlemaps.a. == PREVIEW UPDATE ERROR: FailedToLaunchAppError: Failed to launch *** ================================== | [Remote] JITError | | ================================== | | | [Remote] CouldNotLoadInputStaticArchiveFile: Could not load static archive during preview: /Users/***/Library/Developer/Xcode/DerivedData/BOA-eiluspltxasszsfkpqrnnsxsjhth/Build/Products/Debug_BOA_Inhouse-iphonesimulator/GoogleMaps.a | | | | path: /Users/***/Library/Developer/Xcode/DerivedData/BOA-eiluspltxasszsfkpqrnnsxsjhth/Build/Products/Debug_BOA_Inhouse-iphonesimulator/GoogleMaps.a | | | | ================================== | | | | | [Remote] XOJITError | | | | | | XOJITError: arm64 slice of /Users/***/Library/Developer/Xcode/DerivedData/BOA-eiluspltxasszsfkpqrnnsxsjhth/Build/Products/Debug_BOA_Inhouse-iphonesimulator/GoogleMaps.a does not contain an archive
9
0
256
1w
Crash When Previewing w/ Struct Binding Reassignment In Constructor
Platform Specs: Xcode 16.2 Swift 6.0.3 iOS 18.2 + iOS Simulator 18.3.1 Issue: Refer to the following code: struct CustomView: View { @Binding var prop: CustomStruct init(prop p: Binding<CustomStruct>) { _prop = p } init(isPreview: Bool) { let p = CustomStruct() _prop = .constant(p) } var body: some View { VStack { Text("hi") } } } #Preview { CustomView(isPreview: true) .preferredColorScheme(.dark) } The first constructor is for normal app functionality (and previews/functions correctly when used with the rest of the app in the ContentView preview tab). The second constructor is for previewing only CustomView in its own preview tab. This constructor does not work when previewing in the same file, as shown above. It triggers an ambiguous crash, stating that the diagnostic log (which obviously provides no clear information) should be checked. I have isolated the issue to be in the Binding reassignment in the second constructor. Replacing CustomStruct with anything but another struct, like an enum or primitive, fixes the issue. Note: This bug only occurs when previewing (either through the #Preview macro or PreviewProvider struct).
2
0
231
3w
Previews due to SwiftData Predicates in Xcode 16.3
My preview crashes whenever I compare my model's value to a constant's stored value. I use struct constants with a stored value as alternatives to enums, (IIRC ever since the beginning) enums never worked at all with .rawValue or computed properties. This crashes when it runs on Xcode 16.3 beta and iOS 18.4 in previews. It doesn't appear to crash in simulator. @Model class Media { @Attribute(.unique) var id: UUID = UUID() @Attribute var type: MediaType init(type: MediaType) { self.type = type } static var predicate: (Predicate<Media>) { let image = MediaType.image.value let predicate = #Predicate<Media> { media in media.type.value == image } return predicate } } struct MediaType: Codable, Equatable, Hashable { static let image: MediaType = .init(value: 0) static let video: MediaType = .init(value: 1) static let audio: MediaType = .init(value: 2) var value: Int } My application crashes with "Application crashed due to fatalError in Schema.swift at line 320." KeyPath \Media.<computed 0x000000034082a33c (MediaType)>.value points to a field (<computed 0x000000034082a33c (MediaType)>) that is unknown to Media and cannot be used. This appears to also occur if I am using a generic/any func and use protocols to access a property which is a simple String, such as id or name, despite it being a stored SwiftData attribute. I filed a bug report, but looking to hear workarounds.
4
0
462
2w
How to await inside SwiftUI a #Preview?
In order to setup a preview, I need to create a Book; to do that, I need to await a function – however, one cannot await inside a Preview: import SwiftUI struct BookView: View { let book: Book var body: some View { VStack { Image(book.thumbnail, scale: 1.0, label: Text(book.title)) } } } #Preview { let url = URL(filePath: "/Users/dan/Documents/Curs confirmare RO.pdf")! // 👇 here, `createBook` should be awaited; but how? let book = createBook(for: url, of: CGSize(width: 254, height: 254), scale: 1.0) BookView(book: book) }
5
0
393
1w
SwiftUI Preview Runtime linking failure
Swift Package: I have an old objc library, that is added as XCFramework to swift package as a binary target. targets: [ .target( name: "CoreServices", dependencies: ["OldContainer"], path: "CoreServices" ), .binaryTarget( name: "OldContainer", path: "Frameworks/OldContainer.xcframework" ), ] This serves the purpose, it builds fine and able to run on simulator. However this framework is breaking the Xcode previews. Error: == PREVIEW UPDATE ERROR: [Remote] JITError: Runtime linking failure Additional Link Time Errors: Symbols not found: [ _OBJC_CLASS_$_SCSecureServicesFactory ] ================================== | [Remote] LLVMError | | LLVMError: LLVMError(description: "Failed to materialize symbols: { (static-Login, { __replacement_tag$1015 }) }") == VERSION INFO: Tools: 16C5032a OS: 23G93 PID: 38675 Model: MacBook Pro Arch: arm64e == ENVIRONMENT: openFiles = [ /Users/../Documents/GitHub/Packages/Login/Sources/Login/LoginView.swift ] wantsNewBuildSystem = true newBuildSystemAvailable = true activeScheme = Launch activeRunDestination = iPhone 16 Pro Max variant iphonesimulator arm64 workspaceArena = [x] buildArena = [x] buildableEntries = [ Login Login ] runMode = JIT Executor == SELECTED RUN DESTINATION: Simulator - iOS 18.2 | iphonesimulator | arm64 | iPhone 16 Pro Max | no proxy == EXECUTION MODE OVERRIDES: Workspace JIT mode user setting: true Falling back to Dynamic Replacement: false Based on the error, SCSecureServicesFactory is an objc file inside the XCFramework. Since this is a binary target, I could not add a swift setting module map flag to the XCFramework. Is there any workaround to get the previews working ? Or Am I blocked until the library is converted into swift ?
4
0
375
1w
Simple console display test - preview not working as expected
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") } } }
2
0
321
Feb ’25
Gathering Required Information for Troubleshooting Xcode Previews or Swift Previews Issues
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
0
0
276
Feb ’25
Xcode Preview Crashes: "xcpreviewagent crashed because Alamofire.framework is missing"
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?
1
1
317
Feb ’25
Preview won't load on Mac-OS/Multiplatform Swift-App
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!
1
0
300
Jan ’25
Unable to display SwiftUI View Previews in a Static Framework target
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.
0
0
363
Jan ’25
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) } }
1
0
307
Jan ’25
Preview and bundle for modular app target
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.
2
0
314
Jan ’25