Read image names from a Resource folder

I have an ios playground that has several images in the Resources folder. All the images have "png" extensions. To read all the names into an array, I was using something like this in a regular ios project that had the images in the Assets folder :


import UIKit
var minions = [String]()
let fm = FileManager.default
let path = Bundle.main.resourcePath
let items = try! fm.contentsOfDirectory(atPath: path)
minions = items.filter{$0.hasSuffix("png")}
print(minions)


That worked great in the ios project, but I can't figure out the magic formula to read the image names in a playground. I'm sure it's something simple but I can't find the answer to save my life! Help!

Accepted Reply

I had also posted this question on the Swift forum and QuinceyMorris gave me the answer:


let paths = Bundle.main.paths(forResourcesOfType: "png", inDirectory: nil)


This works for ios and macOS playgrounds. Thanks Quincey!

Replies

I haven't found a way to read the Resources directory in an ios playground, but it's simple in a macOS playground....

import Cocoa
var items = [String]()
let fm = FileManager.default
let strPath = "/Users/yourUSERname/Documents/SWDevelopment/SwiftStuff/Practice_Files/YourPlaygroundName.playground/Resources/"
let directoryContents = try? fm.contentsOfDirectory(atPath: strPath)
items = directoryContents ?? []
print(items)

You can find the full path address by selecting the 'Resources' folder in the navigation panel on the left, and reading it from the identity inspector in the right side panel. There must be a way to get the resource list in ios!!

I had also posted this question on the Swift forum and QuinceyMorris gave me the answer:


let paths = Bundle.main.paths(forResourcesOfType: "png", inDirectory: nil)


This works for ios and macOS playgrounds. Thanks Quincey!

Why is this answer showing up in 2021? Apple engineers need to figure out how to make your forums useful. I have never found a useful solution to a problem via this forum.