Xcode Previews

RSS for tag

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

Xcode Previews Documentation

Posts under Xcode Previews tag

162 Posts
Sort by:
Post marked as solved
1 Replies
894 Views
Hello, I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview. /// Entity data for use with canvas previews. static var preview: Entity1 {         let entities1 = Entity1.makePreviews(count: 1)         return entities1[0] } @discardableResult static func makePreviews(count: Int) -> [Entity1] {         var contents = [Entity1]()         let viewContext = PersistenceController.preview.container.viewContext         let persistenceController = PersistenceController.shared         for index in 0..<count {             let entities1 = Entity1(context: viewContext)             entities1.id = UUID()             entities1.title = "Amazing day!"             let photo = Photo(context: viewContext)             let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()             photo.linkedToJournal = journal             let thumbnail = Thumbnail(context: viewContext)             let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)             thumbnail.data = thumbnailData             thumbnail.photo = photo             let photoDataObject = PhotoData(context: viewContext)             photoDataObject.data = imageData             photoDataObject.photo = photo             contents.append(entities1)         }         return contents } You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview. Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!
Posted
by
Post not yet marked as solved
3 Replies
2.6k Views
Recently have been working on this project just fine... had an app throw a warning for some malware called InstallCore. Removed the malware and now I am getting this on every preview, regardless of the device preview type. I've tried clearing derived data, cache, etc. No dice. Could not install the preview host "AppName.app" on iPhone 14 Pro Max: Failed to get parent identifier for BUNDLEIDENTIFIER.
Posted
by
Post not yet marked as solved
3 Replies
873 Views
Since updating to Big Sur 11.7.5 I am unable to preview any Views or run the Playground both continue to create Crash Reports until Xcode is stopped. The Preview panel remains blank or the Playground never runs. Crash Report attached below which indicates that the update has moved a Library called AddressBook and Xcode can no longer locate it. NPKCompanionAgent_2023-04-06-140115_Johns-iMac.crash
Posted
by
Post not yet marked as solved
2 Replies
890 Views
I have an app with some SwiftUI Views. When using preview in Xcode, Xcode creates many instances of the previews. Then I quit Xcode, but the previews are not quit. I have to force quit them in Menu -> Apple Icon Menu -> Force Quit. Has anyone seen the same thing? How to solving it? Xcode 14.3 (14E222b) macOS Ventura 13.3.1 (a) (22E772610a) Mac mini M1 16G 512G
Posted
by
Post not yet marked as solved
1 Replies
707 Views
Hello, I've completed the Landmarks App Apple Developer tutorial, since finishing it I decided to create a project using the .JSON code from the project. I've wrote the code in an identical layout as the tutorial, however I am receiving the error - Couldn't parse lesssonData.json as array - when trying to load a preview and the app builds successfully but crashes when I launch it. Below is the code, any help is appreciated! LessonList.swift import SwiftUI struct LessonList: View { var lesson: Lesson var body: some View { VStack { List { Section { ForEach(lessons, id: \.self) { lesson in Label(lesson.name, systemImage: "house") } } Section { Label("Hello World!", systemImage: "globe") } } } } } struct LessonList_Previews: PreviewProvider { static var lessons = ModelData().lessons static var previews: some View { LessonList(lesson: lessons[0]) } } ModelData.swift import Foundation import Combine final class ModelData: ObservableObject { @Published var lessons: [Lesson] = load("lessonData.json") } var lessons: [Lesson] = load("lessonData.json") func load<T: Decodable>(_ filename: String) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { let decoder = JSONDecoder() return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") // Error on this Line } } lessonData.JSON [ { "id":"1001", "lessonNo":"Lesson 1", "name":"Introduction to Photography", "category":"Introduction", }, { "id":"1002", "lessonNo":"Lesson 2", "name":"Negative and Positive Space", "category":"Introduction", }, { "id":"1003", "lessonNo":"Lesson 3", "name":"Introduction to Camera Angles", "category":"Introduction", }, { "id":"1004", "lessonNo":"Lesson 4", "name":"Lighting and Framing", "category":"Beginners", }, { "id":"1005", "lessonNo":"Lesson 5", "name":"Still Photography", "category":"Beginners", }, { "id":"1006", "lessonNo":"Lesson 6", "name":"Motion Photograhy", "category":"Beginners", }, { "id":"1007", "lessonNo":"Lesson 7", "name":"Aperture and F-Stops", "category":"Intermiediate", }, { "id":"1008", "lessonNo":"Lesson 8", "name":"Shutter Speeds", "category":"Intermiediate", }, { "id":"1009", "lessonNo":"Lesson 9", "name":"Advanced Framing", "category":"Advanced", }, { "id":"1010", "lessonNo":"Lesson 10", "name":"Advanced Aperture, F-Stops and Shutter Speeds", "category":"Advanced", }, ]
Posted
by
E-K
Post not yet marked as solved
1 Replies
831 Views
Even though the code is 100% works in the simulator, the preview canvas gets "Cannot preview in this file" error more often. How could I get the issue sorted? The issue is sorted after restarting the xcode several times. I tried to attache the generated report as a zip file, but it does not support to attach.
Posted
by
Post not yet marked as solved
1 Replies
1.8k Views
Can't compile existing project with new #Preview macros. Get: 'Preview' is only available in application extensions for iOS 17.0 or newer And because macros generate struct I can't use #available to fix this. Does anyone have any ideas how to fix this? I guess the only solution is to create new macros that will work like #available(iOS 17) { code } and remove the code for older iOS?
Posted
by
Post not yet marked as solved
1 Replies
906 Views
It keeps saying "iOS 17.0 Not Installed" and I cannot build and run my app. When I click the "GET" button, a new window popped up and it clearly stated that iOS 17.0 Simulator was installed. I already tried reinstalling Xcode, but the problem is still there. Any suggestion is appreciated!
Posted
by
Post not yet marked as solved
0 Replies
553 Views
I have been working on a 3x3 Rubik's cube app for iOS, and I have a timer in it. Whenever I try to add a time and save the context in a preview, it gives an error. func addTime(){ print("Started") formatTime() print("Formatted") withAnimation(){ print(formattedTime) let time = Time(context: viewContext) time.time = formattedTime print(time.time!) do{ print("dostart") try viewContext.save() print("saved") }catch{ let error = error as NSError print("An error occurred: \(error)") fatalError("An error occurred: \(error)") } } } This is the function that adds the time and saves the context.(The prints were for debugging purposes) When this function runs while testing in the preview, the do/catch returns "An error occurred: Foundation._GenericObjCError.nilError" When I try to run this in the simulator, it gives this error in Persistence.swift: If you need it, here is my entire ContentView.swift: import SwiftUI import CoreData var scrambles = ["R' B' L U' B2 D B' D' L R B L2 D' B L' U L2 B2 L B2 R' F L2 B' F' U2 B F' L2 F2", "D' B' L B' F L' B2 U' R2 D' U' L' D' R' F L U2 F' R2 D' B2 L' R' B' L R' U F L B2", "L R B' D' L D' U L2 R' B2 L' D2 U2 R' D' U' L D F' L2 D2 F D2 L' D' U' B' F2 U' B'", "U L2 R D' B2 D2 R2 D2 L2 R U2 R' U L2 D' F' D R B' F2 L' F' L B2 F' D' L R' F2 D"," D' U F L' R' U2 R' D B2 F U' L2 D2 B' L2 B2 R' F' D' U B' L' R' B' F L' B' L R2 D", "D2 U' F2 D' U' B2 F' U' R D2 U R2 D2 R2 U L B F2 D2 U2 B F2 L U2 F' U2 R D' L F'", "F D' U B F2 U' F' L2 B2 F2 U B2 F2 D' B' F' L' R2 B D U' B2 F' L' R B' U2 R2 D2 F'", "B F U2 B2 L U B F L2 R F' L2 F' U2 R B U' B2 U2 B' U2 L R D' U2 B' D L R' U"] var starts = ["Start", "Stop"] struct ContentView: View { @State var start = false @State var startstop = "Start" @State var watch = stopwatch() @State var elapsedTime: Int = 0 @State var timeToSave: Int = 0 @State var minutes: Int = 0 @State var seconds: Int = 0 @State var milliseconds: Int = 0 @State var formattedTime: String = "" @Environment(\.managedObjectContext) private var viewContext @FetchRequest(entity: Time.entity(), sortDescriptors: []) private var timecd: FetchedResults&lt;Time&gt; var body: some View { NavigationView{ VStack{ Text("CubeTimer") .font(.largeTitle) .fontWeight(.bold) .padding(2) Text(scrambles.randomElement()!) .multilineTextAlignment(.center) .padding(.top, 125.0) .padding(.leading, 15) .padding(.trailing, 15) .font(.title) .fontWeight(.bold) if start{ watch .padding(.top, 30) .fontWeight(.bold) .onAppear{ startstop = "Stop" watchToggle() } var timer: Timer { Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) {_ in elapsedTime += 1 //print("\(minutes).\(seconds)") print("called") print(elapsedTime) //figure out how to stop timer and save time to core data } } } Button(action: { start.toggle() if start == false{ timeToSave = elapsedTime print(timeToSave) print(elapsedTime) watchToggle() buttonToggle() addTime() } //print(start) }){ Text(startstop) }.padding(.top, 7) .font(.system(size: 30)) Spacer() //figure out how to stop timer and save time to core data } List{ ForEach(timecd){time in Text(time.time ?? "Not found") } } } } func buttonToggle(){ if start{ startstop = "Stop" }else{ startstop = "Start" } } func watchToggle(){ print("runs") watch.toggleRun() watch.testForIsRunning() //print(watch.isRunning) } func formatTime(){ print("Formatting") print(timeToSave) minutes = timeToSave / 6000 seconds = (timeToSave % 6000) / 100 milliseconds = timeToSave % 100 print(minutes) print(seconds) print(milliseconds) formattedTime = "\(minutes):\(seconds).\(milliseconds)" } func addTime(){ print("Started") formatTime() print("Formatted") withAnimation(){ print(formattedTime) let time = Time(context: viewContext) time.time = formattedTime print(time.time!) do{ print("dostart") try viewContext.save() print("saved") }catch{ let error = error as NSError print("An error occurred: \(error)") fatalError("An error occurred: \(error)") } } } func buttontext(){ if start{ startstop = "Stop" }else{ startstop = "Start" } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } Could somebody please help me resolve this issue?
Posted
by
Post marked as solved
2 Replies
1.4k Views
Greetings... I am trying to use @Namespace for my matchedGeometryEffect use case. prior to Xcode 15 beta the following code worked just fine: struct ChapterItem_Previews: PreviewProvider { @Namespace static var namespace static var previews: some View { ChapterItem(namespace: namespace, show: .constant(true)) } } However trying to do the same within the new Xcode 15 beta #Preview Macro #Preview { @Namespace var namespace ChapterItem(namespace: namespace, show: .constant(true)) } produces the following error message: Ambiguous use of 'Preview(_:traits:body:)' May I kindly get assistance on the proper way I can get this to work in Xcode 15 beta? Please be as detail as you can since I'm still new to swiftUI as well Thank You.
Posted
by
Post marked as solved
8 Replies
2.7k Views
Hello! I can't preview the SwiftUI views of watchOS target in Xcode 15 beta 1, when the containing iOS app has a SPM dependency. Reproducing steps: Create a new watchOS app project (with a companion iOS app) in Xcode 15. Both iOS and watchOS ContentView can be previewed at this step. Add a Swift package to the iOS target (the package should be an iOS-specific package, not a watchOS one, for example, https://github.com/siteline/SwiftUI-Introspect) After you add the static library to iOS target, the watchOS preview no longer work anymore. If you check the error message, you can find the Xcode preview attempt to build the iOS package against watchOS SDK.
Posted
by
Post not yet marked as solved
8 Replies
2.9k Views
Has anyone figured out how to generate sample data for a Preview Container that contains relationships? I've tried numerous ways to get a relationship, but have not had any success. I've searched around the forms and the internet to see if I can find anything, but haven't had any luck. Here is what I have defined for my previewContainter and the sample data structure. I've followed the same pattern that is found in WWDC2023 Build an app with SwiftData. The books and tags are created just fine in memory, and in my SwiftUI previews, I can see these items. Here is what I currently have, but I have also tried running a query after SampleData.books.forEach(container.mainContext.insert(object: )) and then using one of the returned items for the relationship, but every query I perform in here returns an empty result. Am I barking up the wrong tree with my approach, or is this a known issue that I have not come across? @MainActor let previewContainer: ModelContainer = { do { let container = try ModelContainer( for: [Project.self, Recipe.self, Tag.self], ModelConfiguration(inMemory: true) ) // Add in sample data SampleData.books.forEach(container.mainContext.insert(object: )) SampleData.tags.forEach(container.mainContext.insert(object: )) SampleData.recipes.forEach(container.mainContext.insert(object: )) return container } catch { fatalError("Failed to create preview container") } }() struct SampleData { static let books: [Book] = { return (1...5).map({ Book(title: "Sample Book #\($0)") }) }() static let tags: [Tag] = { return (1...5).map({ Tag(name: "Sample Tag #\($0)") }) }() static let recipes: [Recipe] = { (1...5).map({ Recipe(name: "Sample Recipe #\($0)", book: Self.books.first!) }) }() } Thanks
Posted
by
Post not yet marked as solved
0 Replies
572 Views
Hey all, I was just wondering what would be the best/easiest way to have a sample for any MusicItem to use in SwiftUI previews. I know I could convert one into a string and then decode (as it conforms to Codable) but maybe there is a way that would make it easier to setup? if not I might file a feedback for this as I think it would be great if all MusicItem structures would have a .example or something like that so for a view you'd have #Preview { SongTitlesView(song: Song.example) }
Posted
by
Post marked as solved
1 Replies
2k Views
Xcode Previews are a great new feature, and I've been adding #Preview blocks to some of my more complex UIKit files so I can tweak their UI without running the app. It's been a blast so far. The only problem is that I apparently have to set my project deployment target to iOS 17.0 to use them at all. If I set it to iOS 16.0, I get these errors: 'Preview' is only available in iOS 17.0 or newer 'init (_:traits:body:' is only available in iOS 17.0 or newer 'UVPreviewRegistry' is only available in iOS 17.0 or newer 'Preview' is only available in iOS 17.0 or newer 'init (_:traits:body:' is only available in iOS 17.0 or newer I tried surrounding #Preview with an @availability block for iOS 17, but got the same errors. My goal is to be able to leave useful #Preview blocks in my source code, but still set my deployment target to iOS 16. Is this possible?
Posted
by
Post not yet marked as solved
3 Replies
2.2k Views
Hiya, I am having issues trying to use previews in the xcode 15 beta, i am using an M2 macbook air with 8gb of ram. I am using MacOS Sonoma and iOS 17.0 Beta 1 and am struggling using previews, the base simulator works but no previews. I am not receiving any error so am very confused. Any help would be majorly appreciated. Thanks, Gus
Posted
by
Post not yet marked as solved
2 Replies
297 Views
Hey guys, So I am just starting out and for the life of me I cannot figure out how to match the preview I am seeing in the apple Landmarks swiftUI tutorial as seen above the phone here: and again when looking at these 2 rows: My live preview settings seem to be at the bottom, and look different from the tutorial: As you can see as well, in my layout I need to click between the 2 views while the tutorial layout shows both at the same time. I have searched all over and can't seem to figure out why they are different. If someone could just let me know I would appreciate it!
Posted
by