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

97 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
139
21h
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
161
3d
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
203
1d
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
259
6d
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
259
5d
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! 🙏🚀
1
1
249
1w
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
390
1w
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
125
1w
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
333
1w
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
253
1w
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
129
2w
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
163
4d
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
248
2w
Which device is used to test Swift Student Challenge submissions?
Hi there, I intend to submit an app playground for the Swift Student Challenge this year. I am currently using the Swift Playgrounds app to develop a playground. Now I understand that when submitting I can choose the option of having my app playground to be tested on Swift Playgrounds on either iPadOS or macOS. But I would also like to know on which screen size is my app going to be tested. Let's say I want my app playground to run on macOS, now is there a way to also select the MacBook model, like 14-inch or 16-inch? This would give the participants a better idea of where the app playground will be tested.
3
1
330
2w
Issues with using ClassifyImageRequest() on an Xcode simulator
Hello, I am developing an app for the Swift Student challenge; however, I keep encountering an error when using ClassifyImageRequest from the Vision framework in Xcode: VTEST: error: perform(_:): inside 'for await result in resultStream' error: internalError("Error Domain=NSOSStatusErrorDomain Code=-1 \"Failed to create espresso context.\" UserInfo={NSLocalizedDescription=Failed to create espresso context.}") It works perfectly when testing it on a physical device, and I saw on another thread that ClassifyImageRequest doesn't work on simulators. Will this cause problems with my submission to the challenge? Thanks
5
1
365
1w
Link in Swift Student Challenge
I intend to participate in the Swift Student Challenge. A link is provided within my application that directs users to an Internet HTML web page. Link(destination: URL(string: "https://url.com")!) { Label("Developer Website - .....com", systemImage: "arrow.right") .shadow(color: Color.white ,radius: 50) } This URL corresponds to my personal web page. Although it is not directly related to the experience interaction within the application, I have decided to include it as it serves as a logo and demonstrates my proficiency in HTML. However, the challenge’s rules stipulate that the evaluation environment is not permitted to connect to the Internet. Consequently, I am concerned that my work may be rejected due to its perceived incompleteness or errors. So should I keep it? Thanks!
1
0
290
2w