Swift Playgrounds

RSS for tag

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

Posts under Swift Playgrounds tag

83 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Swift Playground Bundle can't find Compiled CoreML Model (.mlmodelc)
I have been attempting to debug this for over 10 hours... I am working on implementing Apple's MobileNetV2 CoreML model into a Swift Playgrounds. I performed the following steps Compiled CoreML model in regular Xcode project Moved Compiled CoreML (MobileNetV2.mlmodelc) model to Resources folder of Swift Playground Copy Paste the model class (MobileNetV2.swift) into the Sources folder of Swift Playground Use UIImage extensions to resize and convert UIImage into CVbuffer Implement basic code to run the model. However, every time I run this, it keeps giving me this error: MobileNetV2.swift:100: Fatal error: Unexpectedly found nil while unwrapping an Optional value From the automatically generated model class function: /// URL of model assuming it was installed in the same bundle as this class class var urlOfModelInThisBundle : URL { let bundle = Bundle(for: self) return bundle.url(forResource: "MobileNetV2", withExtension:"mlmodelc")! } The model builds perfectly, this is my contentView Code: import SwiftUI struct ContentView: View { func test() -> String{ // 1. Load the image from the 'Resources' folder. let newImage = UIImage(named: "img") // 2. Resize the image to the required input dimension of the Core ML model // Method from UIImage+Extension.swift let newSize = CGSize(width: 224, height: 224) guard let resizedImage = newImage?.resizeImageTo(size: newSize) else { fatalError("⚠️ The image could not be found or resized.") } // 3. Convert the resized image to CVPixelBuffer as it is the required input // type of the Core ML model. Method from UIImage+Extension.swift guard let convertedImage = resizedImage.convertToBuffer() else { fatalError("⚠️ The image could not be converted to CVPixelBugger") } // 1. Create the ML model instance from the model class in the 'Sources' folder let mlModel = MobileNetV2() // 2. Get the prediction output guard let prediction = try? mlModel.prediction(image: convertedImage) else { fatalError("⚠️ The model could not return a prediction") } // 3. Checking the results of the prediction let mostLikelyImageCategory = prediction.classLabel let probabilityOfEachCategory = prediction.classLabelProbs var highestProbability: Double { let probabilty = probabilityOfEachCategory[mostLikelyImageCategory] ?? 0.0 let roundedProbability = (probabilty * 100).rounded(.toNearestOrEven) return roundedProbability } return("\(mostLikelyImageCategory): \(highestProbability)%") } var body: some View { VStack { let _ = print(test()) Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") Image(uiImage: UIImage(named: "img")!) } } } Upon printing my bundle contents, I get these: ["_CodeSignature", "metadata.json", "__PlaceholderAppIcon76x76@2x~ipad.png", "Info.plist", "__PlaceholderAppIcon60x60@2x.png", "coremldata.bin", "{App Name}", "PkgInfo", "Assets.car", "embedded.mobileprovision"] Anything would help 🙏 For additional reference, here are my UIImage extensions in ExtImage.swift: //Huge thanks to @mprecke on github for these UIImage extension function. import Foundation import UIKit extension UIImage { func resizeImageTo(size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) self.draw(in: CGRect(origin: CGPoint.zero, size: size)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resizedImage } func convertToBuffer() -> CVPixelBuffer? { let attributes = [ kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue ] as CFDictionary var pixelBuffer: CVPixelBuffer? let status = CVPixelBufferCreate( kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attributes, &pixelBuffer) guard (status == kCVReturnSuccess) else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext( data: pixelData, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) UIGraphicsPushContext(context!) self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) UIGraphicsPopContext() CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } }
5
1
2k
Feb ’24
Swift Playgrounds version of 'Copy Bundle Resources' build phase
Hi! I'm participating in the Swift Student Developer competition this year, which requires developers to present a Swift Playground to Apple. I'm used to making normal Xcode projects, and am having trouble finding a Swift Playgrounds version of the Copy Bundle Resources build phase (I don't think it is possible to edit build phases in a Swift Playground). I created a '.usdz' file from a 3D model I designed using Reality Converter and added it to the root of my Swift Playground project. I access the file programmatically from the App Bundle like so (fileName is a non-nullable String): guard let path = Bundle.main.path(forResource: fileName, ofType: "usdz") else { fatalError("Couldn't find the USDZ file.") } At runtime, this throws the Couldn't find the USDZ file error, as the file isn't being copied to the App Bundle. In a normal Xcode project, according to this StackOverflow question, I can get xcodebuild to copy my file over by specifying it in the Copy Bundle Resources build phase, however, in a Swift Playground (required by Apple), I am restricted from modifying Xcode's buildphases (the option is not present when clicking on the default target - the only options are General, Signing & Capabilites and Package Dependencies). How can I ensure that resources are copied over to the App Bundle at buildtime in a Swift Playground? If this is not possible, are there any other options besides using the Bundle.main.path API for accessing the USDZ file (to load a QuickLook preview) at runtime?
2
0
1.1k
Jan ’24
Swift Playgrounds lessons not showing Swift 5.9
Hey folks! I remember some weeks/months ago to get some lessons with updated Swift 5.9, I'm just not sure if this happened while I was using Swift Playgrounds beta from TestFlight. Anyways, I went back to study using Swift Playgrounds and all the lessons are using Swift 5.8 here. I don't know what happened or how can I have the lessons updated again. Anyone else noticed this issue? Any tip on how to solve it?
7
0
1.2k
Jan ’24
iOS 17 Features being depreciated
I am currently working on my project for the Swift Student Challenge 2024. I am trying to implement a feature (.defaultScrollAnchor on a ScrollView in this instance). However, when trying to build/run the app in Xcode it says that .defaultScrollAnchor is only compatible with iOS 17. If I try to use .scrollPosition(initialAnchor: ), it also doesn't work (likely because it has been depreciated). I printed the system version as suggested in another post, and it showed the simulator was running iOS 17.2. Why can't the app build/run with this feature if the simulator is running iOS 17.2? MacBook Pro 14" 2021 M1 Pro Xcode Version 15.1 macOS Sonoma 14.0
1
0
1.6k
Jan ’24
Having issues with SwiftUI ForEach usage
The code below is a json parser example. I used the quick type website to build my structs for reading in the json. All that code works but I am having an issue with looping thru the data read. I am trying to read this is a view, so I can not use a for statement. I am having issues learning how to use the ForEach Statement to loop on the contacts in this json data and print the firstName, lastName for each contact. This is the Code let data1JSON = """ [ { "data": { "viewer": { "__typename": "Member", "id": 123, "firstName": "d", "lastName": "a", "emailAddress": "w" }, "league": { "id": 1111, "name": "a", "slug": "b", "isMine": true, "logo": "g", "homePageUrl": "bA", "facebookUrl": "www.facebook.com/B", "phone": "1", "contacts": [ { "id": 12, "firstName": "", "lastName": "d", "phone": null, "__typename": "Contact" }, { "id": 10, "firstName": "", "lastName": "c", "phone": null, "__typename": "Contact" } ], "__typename": "League" } } } ] """ // MARK: - ApaResultElement struct ApaResultElement: Codable { let data: DataClass } // MARK: - DataClass struct DataClass: Codable { let viewer: Viewer let league: League } // MARK: - League struct League: Codable { let id: Int let name, slug: String let isMine: Bool let logo: String let homePageURL, facebookURL, phone: String let contacts: [Viewer] let typename: String enum CodingKeys: String, CodingKey { case id, name, slug, isMine, logo case homePageURL = "homePageUrl" case facebookURL = "facebookUrl" case phone, contacts case typename = "__typename" } } // MARK: - Viewer struct Viewer: Codable { let id: Int let firstName, lastName: String let phone: JSONNull? let typename: String let emailAddress: String? enum CodingKeys: String, CodingKey { case id, firstName, lastName, phone case typename = "__typename" case emailAddress } } typealias ApaResult = [ApaResultElement] // MARK: - Encode/decode helpers class JSONNull: Codable, Hashable { public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { return true } public var hashValue: Int { return 0 } public init() {} public required init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if !container.decodeNil() { throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encodeNil() } } let decoder = JSONDecoder() let leagueView = data1JSON.data(using: .utf8)! do { try decoder.decode([ApaResultElement].self, from: leagueView) print("success") } catch { print("Error found => \(error)") } let d1 = try decoder.decode([ApaResultElement].self, from: leagueView) // This is where I need help to loop the json to extract all the data // I see that I need to loop on each array stuct to do that. I have looked for a good tutorial on ForEach, but none of the sites I found help me look on this JSON Data. I am new to swift and the autocomplete feature, so any tips using Apple Developer Documentation or the Code Complete would also be appreciated. Thanks
2
0
1.3k
Dec ’23
share photo to facebook but no dialog shows
Hi, Everyone I set up a class for sharing photos to facebook. The codes of the class are as following. But when I call the function "shareToFacebook", there is no dialog to show. What's the issue in these codes? I am using iOS 17.0, Xcode The guide from Facebook hasn't updated. import SwiftUI import FBSDKShareKit import FacebookShare @Observable class ShareFacebook { var content = SharePhotoContent() var images : [UIImage] = [] var photos : [SharePhoto] = [] func shareToFacebook() { for image in images { let photo = SharePhoto( image: image, isUserGenerated: true ) photos.append(photo) } content.photos = photos let dialog = ShareDialog( viewController: UIApplication.shared.currentUIWindow()?.rootViewController, content: content, delegate: nil ) dialog.show() } } //button for sharing //Sharing to Facebook Button { for image in photos { let image = UIImage(data: image.imageData) sharedPhotos.append(image ?? userViewModel.render(image: Image("photoForNil"))! ) } shareToFacebook.images = sharedPhotos shareToFacebook.shareToFacebook() }label: { Image("share") .resizable() .frame(width:18, height: 18) .padding(.trailing,30) }
0
0
478
Dec ’23
Show Table in SwiftUI Playground
I am trying to generate a simple playground to display Table structure with several TableColumns. Basically, generated a new blank playground; add import statements for SwiftUI and PlayGround support; add structure for content view and a statement for invoking that view as: `PlaygroundPage.current.setLiveView(ContentView()) In general, all of the view components work as expected EXCEPT for the table structure which does not display anything. Its basic structure is: Table(rows, selection: $selRow) { TableColumn("ID") {Text(String($0.id))} TableColumn("Name", value: \.nt) } where "rows" is an array of the structure TRow: struct TRow : Identifiable { var id:Int var num:Int var nt:String } Is there some special trick to allowing a SwiftUI Table to be displayed in Playground?
1
0
603
Dec ’23
Not able to run Playground Basics from Swift Explorations
Hi, I wanted to learn basics on developing in iOS and started with Swift Explorations. I have installed Xcode 15.0.1 and running it on Ventura 13.5.1. When I execute the Playgroung Basics.playground file, I get an error message saying "Failed to attach to stub for playground execution". Any clue as to why that might be? I am able to create my own playground and execute it properly. I searched around but could not find anything on the topic (other than disablig Rosetta which is not an option as far I can tell in my case; don't see that checkbox under Get Info). Any pointer would be welcome. Cheers, Piloo
2
0
530
Dec ’23
Swift Regex crashes when trying to get a simple string
I'm trying to create a simple Regex Builder to parse a timestamp in hh:mm:ss or mm:ss format, a " - " separator, and then a string. I'm trying to use the new Swift RegexBuilder however it doesn't seem to work. It compiles but crashes when running when trying to get the text portion. Example code in a single playground preview file for reference: import SwiftUI import RegexBuilder struct RegexTestView: View { var string: String { let timecode = Regex { Optionally { OneOrMore(.whitespace) } // timecode section Optionally { Capture { OneOrMore(.digit) } transform: { match in Int(match) } ":" } TryCapture { OneOrMore(.digit) } transform: { match in Int(match) } ":" // seconds TryCapture { OneOrMore(.digit) Optionally { // miliseconds "." OneOrMore(.digit) } } transform: { match in TimeInterval(match) } // separator " - " Capture { // WHY CAN'T I GET THE REMAINING TEXT???? Any attempts I make to get this result in a crash. OneOrMore(.any) } transform: { match in String(match) } } let tests = [" 222:45:23.2 - foo","2:34:22 - bar"," 2:08 - baz","2:32.18","2:45:23.2 - what"] var results = "" for test in tests { guard let match = test.wholeMatch(of: timecode) else { results += "MATCH NOT FOUND" continue } results += """ •••• \(match.0) \(String(describing: match.1)) \(String(describing: match.2)) \(String(describing: match.3)) """ /* // Adding this line to the above crashes \(String(describing: match.4))\n */ } return results } var body: some View { Text(string) } } #Preview("Regex") { RegexTestView() }
1
0
632
Nov ’23
Xcode playground projects don't supporting iOS 17?
I wanted to take some code I had written in an Xcode project and put it in a playground, though while working on a playground in Xcode, it's showing errors that some lines of code are only supported in iOS 17. I'm updated to the most recent version. Is there any reason why my playgrounds are showing this error? I assume it might be due to the playground wanting to make sure the app works on older OSs, but a lot of the code I used has no previous counterpart. If this is the case, is there any way I can get around this? Thanks for taking the time to check this out.
1
0
669
Nov ’23
"public headers ("include") directory path for 'Guide' is invalid or not contained in the target" error
Hi, I have a problem with making a swift playgrounds app walkthrough. I followed the steps exactly and modified my Package.swift a bit (in the targets section): .executableTarget(name: "App", dependencies: ["Guide"], path: "App"),         .target(             name: "Guide",             path: "Guide",             resources: [             .process("Guide.tutorial"),             ]) Now when I open the project in Playgrounds I get this error: public headers ("include") directory path for 'Guide' is invalid or not contained in the target Any help would be appreciated. Thanks
4
0
2.6k
Oct ’24