Swift Playground

RSS for tag

Learn and explore coding in Swift through interactive learning experiences on the Swift Playground app for iPadOS and macOS.

Posts under Swift Playground tag

94 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

‘Keep going with apps’ Crash during Creature Add steps
Hello fellow Techies! I am currently doing the Swift Playgrounds “Keep Going with Apps” on my iPad Pro. Everything has been going as designed until I got to the ‘Add and Delete Creatures‘ module. The lesson concludes with being able to add a creature to your list in the CreatureZoo. When you run the app from the playground, you can fill out the fields and tap ‘Add’ and that is when the app dims and after 5 seconds I get the notification that the app has an unknown crash. I have reviewed the lessons leading up to it, but I can’t find anything wrong. (Full Disclosure: I really have no clue what I am looking at some of time.) Has anyone else ran into this? `import SwiftUI import Guide struct CreatureEditor: View { //#-learning-code-snippet(defineVariablesCreatureEditor) //#-learning-code-snippet(environmentValue) @State var newCreature : Creature = Creature(name: "", emoji: "") @EnvironmentObject var data : CreatureZoo @Environment(.dismiss) var dismiss var body: some View { SPCAssessableGroup(view: self) { VStack(alignment: .leading) { Form { Section("Name") { //#-learning-code-snippet(addACreatureEditorTextField) TextField("What is your monster's name?", text: $newCreature.name) } Section("Emoji") { TextField("What does your monster look like?", text: $newCreature.emoji) } Section("Creature Preview") { CreatureRow(creature: newCreature) } } } .toolbar { ToolbarItem { Button("Add") { data.creatures.append(newCreature) dismiss() } } } //#-learning-code-snippet(addButtonToToolbar) } } } struct CreatureEditor_Previews: PreviewProvider { static var previews: some View { NavigationStack() { CreatureEditor().environmentObject(CreatureZoo()) } } }’
4
0
146
4d
Swift Playground 4.6 - App Fails to Run with import AppIntent
Hi everyone, I’ve been developing an app using Swift Playgrounds, and it was working fine in version 4.5. However, after updating to Swift Playground 4.6, the app no longer runs. After some testing, I found that the issue occurs when import AppIntent is included. Here’s a simple example: import SwiftUI //import AppIntents // <- If this line is included, Preview and Run fail. @main struct MyApp: App { var body: some Scene { WindowGroup { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") } } } Has anyone else encountered this issue? Thanks!
2
0
218
1w
Swift Playgrounds 4.6 removes support for libraries?
I had several library projects that were working in Swift Playgrounds < 4.6 but I get several duplicate compilation errors and previews will not build in Swift Playgrounds > 4.6. Does anyone know how to fix this issue? Example project: This project builds and runs fine under Swift Playgrounds 4.5.1 however it will not run complaining multiple commands produce generated output files under Swift Playgrounds 4.6.1, 4.6.2, and 4.6.3. https://github.com/kudit/Compatibility Download this repository and add the extension ".swiftpm" to the folder and double click to open in Swift Playgrounds. If running on earlier Swift Playgrounds you can see there are no errors and previews work great (on both macOS and iPadOS versions of Swift Playgrounds 4.5.x). However, on Swift Playgrounds 4.6.x, previews will not display. Are embedded libraries not support anymore? This would be very disappointing. I posted this as a Feedback weeks ago with no response: FB16509699
1
0
236
3w
PlaygroundSupport no longer available for Playground apps
In Swift Playground 4.6.2 the package PlaygroundSupport is no longer available to Playground apps. The following test previously permitted apps run in the Playground vs compiled in XCode to support different behavior: #if canImport(PlaygroundSupport) container = NSPersistentContainer(name: "myApp", managedObjectModel: Self.createModel()) #else container = NSPersistentCloudKitContainer(name: "myApp") #endif Since Swift Playground 4.6.2 the PlaygroundSupport package is no longer available for app projects in Playgrounds. Is there a different compile type test which can be used to differentiate compilation for Swift Playground apps ? I am currently having to use a runtime workaround (below) but would prefer a compile time test is an alternative is available. public static var inPlayground: Bool { if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").contains("swift-playgrounds") }) { return true } else { return false } }
1
0
338
Feb ’25
Bundle Display Name Swift Playgrounds
I am attempting to use the AVSpeechSynthesizer to include text to speech in my Swift Playgrounds project, but when I attempt to use it on my IPhone i get the following errors: It works just fine on the simulator, but no audio is produced when I run it on-device. Is there a way to set this "bundle display name" within Swift Playgrounds, or are there any workarounds? My code: import AVFoundation class Speaker { let synthesizer = AVSpeechSynthesizer() func speak() { let utterance = AVSpeechUtterance(string: "Test, I am the speaker") synthesizer.speak(utterance) } }
1
1
312
Feb ’25
Playground app on MacOS
Hi! I have a concern for the SSC: I worked on the Playground app, but on MacOS. My app has been developped to be firstly used on a mac, as the playground app let you directly download your app on you mac and act as a real one. When i wanted to submit, I noticed there is nowhere to specify whether your app should be tested on iPad or on MacBook. I saw Playground apps would be tested on an iPad, does it mean I have to refactor my app to work on one, or i can mention on a comment that it is a MacOS app, and should therefore be tested on a mac? Thanks for your help on this
1
0
393
Feb ’25
Regarding AR App Submission Built in Xcode - Swift Student Challenge submission
Hello guys, I have a question regarding the submission requirements. My app uses ARKit and requires Metal files for shaders, which are not supported by Swift Playgrounds. Therefore, I developed my app using Xcode. (swift playgrounds returning error for metal file) Since my app relies on a real device for proper functionality, I would like to know if, under these circumstances, the scene build is performed by Xcode. If the build were instead done by Swift Playgrounds, my scene would not function correctly. I'm asking that because of this note Thank you for your time and assistance.
1
0
408
Feb ’25
Metal not working in Swift Playgrounds (SSC Scene)
Hi everyone, I'm currently working on a Swift Playgrounds project where I need to incorporate a Metal shader file. However, when I tried to include my shader file (PincushionShader.metal), I encountered the following error: Is it possible to use Metal shader files within Swift Playgrounds, it is really important for my swift student challenge scene? If not, are there any workarounds or recommended approaches for testing Metal shaders in a similar environment? Any guidance or suggestions would be greatly appreciated!
3
0
476
Feb ’25
Swift student challenge assessment query!!!
I was just filling the submission for the swift student challenge and there is a note below adding the zip file saying Note: Xcode app playgrounds are run in Simulator. Now my xcode app playground(.swiftpm) is an AR app and needs an ipad or an iphone to run . So will my submission still be eligible for assessment and checked on ipad???
1
0
532
Feb ’25
Xcode: Skipping Duplicate Build File in Compile Sources in a .swiftpm Project – How to Fix?
I'm trying to add Assets.xcassets to a .swiftpm project, but I'm getting the warning: ⚠️ Ignoring duplicate build file in build source build phase (Just to know, that is about developing in XCODE, in Swift Playgrounds does not appear it, even in this second being harder to setting up) The problem is that there are no “Build Phases” in XCODE to remove duplicate files manually. I've already tried adding the path of Assets.xcassets in the resources property of Package.swift, like: .executableTarget( name: "AppModule", path: ".", resources: [ .process("Assets.xcassets") ] ) Even so, the warning persists. Does anyone know how to solve this? Is there any way to remove duplicate references or force a cleanup of the Swift Package Manager cache to fix it? I appreciate any tips! 🙏🚀
2
2
444
Feb ’25
Question about how to access to camera on Swift Playground
When I was working on my project for Swift Student Challenge, I found an interesting fact regarding camera access. If I create an App project on Xcode, the camera capture works well on it. However, if I copied and pasted the code on an App Playground project on Xcode, it crashed and output several errors. I am wondering why this is happening.
1
0
395
Feb ’25
Playground for more than 3 minutes to participate in the Swift Student Challenge
I am currently preparing my submission for the Swift Student Challenge, and my app playground is quite comprehensive. Based on my estimations, it may take approximately 4 to 5.5 minutes for the reviewers to fully experience the interactive elements of my app. Every component is integral to the overall experience, and I would prefer not to remove any content, as each part not only contributes to the overall interactivity but also effectively demonstrates my abilities across different technical and creative domains. However, I noticed the guideline on https://developer.apple.com/swift-student-challenge/eligibility stating that the interactive scene should be “experienced within three minutes.” While this does not appear to be a main requirement, my app playground significantly exceeds this timeframe. Could you kindly clarify whether exceeding the three-minute guideline could result in my submission being rejected, or if it might negatively impact the evaluation process? I would greatly appreciate any insights you can provide. Thank you for your time and consideration. I look forward to your response.
2
0
577
Feb ’25
Playground SwiftUI on iPad wont save .png image using fileExporter.
The SwiftUI Playground code below demonstrates that a .jpeg image can be read and written to the iOS file system. While, a.png image can only be read; the writing request appears to be ignored. Can anyone please tell me how to code to save a .png image using SwiftUI to the iOS file system. Code: import SwiftUI import UniformTypeIdentifiers /* (Copied from Playground 'Help' menu popup.) UIImage Summary An object that manages image data in your app. You use image objects to represent image data of all kinds, and the UIImage class is capable of managing data for all image formats supported by the underlying platform. Image objects are immutable, so you always create them from existing image data, such as an image file on disk or programmatically created image data. An image object may contain a single image or a sequence of images for use in an animation. You can use image objects in several different ways: Assign an image to a UIImageView object to display the image in your interface. Use an image to customize system controls such as buttons, sliders, and segmented controls. Draw an image directly into a view or other graphics context. Pass an image to other APIs that might require image data. Although image objects support all platform-native image formats, it’s recommended that you use PNG or JPEG files for most images in your app. Image objects are optimized for reading and displaying both formats, and those formats offer better performance than most other image formats. Because the PNG format is lossless, it’s especially recommended for the images you use in your app’s interface. Declaration class UIImage : NSObject UIImage Class Reference */ @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ImageFileDoc: FileDocument { static var readableContentTypes = [UTType.jpeg, UTType.png] static var writableContentTypes = [UTType.jpeg, UTType.png] var someUIImage: UIImage = UIImage() init(initialImage: UIImage = UIImage()) { self.someUIImage = initialImage } init(configuration: ReadConfiguration) throws { guard let data = configuration.file.regularFileContents, let some = UIImage(data: data) else { throw CocoaError(.fileReadCorruptFile) } self.someUIImage = some } func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { switch configuration.contentType { case UTType.png: if let data = self.someUIImage.pngData() { return .init(regularFileWithContents: data) } case UTType.jpeg: if let data = self.someUIImage.jpegData(compressionQuality: 1.0) { return .init(regularFileWithContents: data) } default: break } throw CocoaError(.fileWriteUnknown) } } struct ContentView: View { @State private var showingExporterPNG = false @State private var showingExporterJPG = false @State private var showingImporter = false @State var message = "Hello, World!" @State var document: ImageFileDoc = ImageFileDoc() @State var documentExtension = "" var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text(message) Button("export") { if documentExtension == "png" { message += ", showingExporterPNG is true." showingExporterPNG = true } if documentExtension == "jpeg" { message += ", showingExporterJPG is true." showingExporterJPG = true } } .padding(20) .border(.white, width: 2.0) .disabled(documentExtension == "") Button("import") { showingImporter = true } .padding(20) .border(.white, width: 2.0) Image(uiImage: document.someUIImage) .resizable() .padding() .frame(width: 300, height: 300) } // exporter .png .fileExporter(isPresented: $showingExporterPNG, document: document, contentType: UTType.png) { result in switch result { case .success(let url): message += ", .\(documentExtension) Saved to \(url.lastPathComponent)" case .failure(let error): message += ", Some error saving file: " + error.localizedDescription } } // exporter .jpeg .fileExporter(isPresented: $showingExporterJPG, document: document, contentType: UTType.jpeg) { result in switch result { case .success(let url): message += ", .\(documentExtension) Saved to \(url.lastPathComponent)" case .failure(let error): message += ", Some error saving file: " + error.localizedDescription } } // importer .fileImporter(isPresented: $showingImporter, allowedContentTypes: [.png, .jpeg]) { result in switch result { case .failure(let error): message += ", Some error reading file: " + error.localizedDescription case .success(let url): let gotAccess = url.startAccessingSecurityScopedResource() if !gotAccess { message += ", Unable to Access \(url.lastPathComponent)" return } documentExtension = url.pathExtension guard let fileContents = try? Data(contentsOf: url) else { message += ",\n\nUnable to read file: \(url.lastPathComponent)\n\n" url.stopAccessingSecurityScopedResource() return } url.stopAccessingSecurityScopedResource() message += ", Read file: \(url.lastPathComponent)" message += ", path extension is '\(documentExtension)'." if let uiImage = UIImage(data: fileContents) { self.document.someUIImage = uiImage }else{ message += ", File Content is not an Image." } } } } }
0
0
254
Feb ’25
Swift Student Challenge table's two questions
I am currently filling out the Swift Student Challenge form, and I have two questions that I hope to get clarified: One of the options asks, “Did you use open source software, other than Swift?” I would like to know what is meant by “open source software” in this context. Does it refer to IDEs (like Xcode) or programming languages and frameworks (such as Python, ARKit)? Are Apple frameworks (e.g., SwiftUI, ARKit, etc.) and certain third-party tools (such as Xcode, Blender, etc.) considered “open source software”? I would like to provide a demo video to ensure that the reviewers can use the app properly and experience all of its features in the shortest amount of time. For certain reasons, I do not plan to play the video directly in the App Playground. Instead, I intend to include a link in the “Comments” section at the end of the form, which will redirect to a webpage (requiring an internet connection) containing the demo video. Will the reviewers be able to view the link and access the video as intended? I would greatly appreciate any responses to these questions!
1
0
517
Feb ’25
Swift Student Challenge Devices / Simulator preferred building device
For the SSDC submission, the app playground must run on Swift Playgrounds 4.5+ or Xcode 16+. Key questions: In Swift Playgrounds, is the app tested on iPadOS or macOS? In Xcode 16+, is the playground tested using Mac Catalyst, an iPad simulator, or an iPhone simulator? The submission form only mentions a simulator but doesn’t specify which one. Can I build an app primarily for iPhone (portrait mode), or is it better to focus on iPad (landscape mode) if that’s the expected testing environment in all cases?
0
1
387
Feb ’25
How to custom swift playground preview application ($title.app) window size
I used Swift Playground to develop application in Mac OS. Also using ZStack I used limited area in full page (using .frame(width: $, height: $)). However using command + R or clicking start button to see preview .app, while non resizing application my ZStack show as cutted. Please tell me how to set preview .app frame size as width, height... The buttom code is ContentView.swift code. @main struct ContentView: App { init() { MyFont.registerFonts() } // @StateObject private var audioPlayer = AudioPlayer() var body: some Scene { WindowGroup { NavigationStack { StartMenuView() .frame(minWidth: 594, maxWidth: 594, minHeight: 1142, maxHeight: 1142) .preferredColorScheme(.dark) // Dark Mod .statusBar(hidden: true) // Hidden Status Bar .edgesIgnoringSafeArea(.all) // Ignoring Safe Area } } .windowResizability(.contentSize) } } Thank you for reading. ![]("https://developer.apple.com/forums/content/attachment/8ad9f219-6caa-49bf-b8c3-e4b7c91ab40f" "title=image.png;width=1050;height=803") ![]("https://developer.apple.com/forums/content/attachment/395ee85e-9543-4bfd-9caf-3ce3c2ca8414" "title=image2.png;width=1104;height=973")
0
0
250
Feb ’25
Is it possible to use Lottie with Swift Package Manager files?
Hi! I wanted to use Lottie in my swiftpm app, but I've been running into errors and I'm not sure if it's possible. When I try to run the app, it crashes and I get errors saying that the library isn't loaded and the files aren't found (basically these: https://github.com/lottie-react-native/lottie-react-native/issues/373 , https://github.com/airbnb/lottie-ios/issues/2233 ). But moving the framework file into the PackageFrameworks folder doesn't work, and also I'm getting the error that swiftpm cannot distribute packages containing binary frameworks and from what I understand that just isn't something that swiftpm can do. So I was wondering if anyone knows any workarounds to this, or if I should just ditch Lottie? Any help or advice would be greatly appreciated!
1
0
316
Feb ’25
Fatal Error in Swift Playground
Fatal Error in Swift Playground Description I'm experiencing a catastrophic error when importing Package Dependency in any Swift Playgrounds that has icon or name that caused the whole Playground won't work anymore with error messages below. I'm current running macOS Sequoia 15.3 (24D60) and Swift Playgrounds 4.6.1. They're all up-to-date. Reproduction Open Swift Playgrounds and and create a new project. Import a package dependency https://github.com/simibac/ConfettiSwiftUI.git Rename the project and add an icon Then you should able the reproduce the problem. I strongly believed that this is a serious bug. You'll find that Assets in the left column are disappeared and appeared Assets.xcassets, you're unable to reveal the Dependency in the column like the reference picture above. The whole Playground is destroyed now and unable to work anymore.
2
0
403
Feb ’25