Search code examples
iosiphoneswiftnsfilemanager

How do I count a number of images in a folder reference in swift


I'm working on an custom emoji keyboard in Swift and I'm having trouble finding and counting the images in a folder reference called "emojis".

EDIT: To clarify my issue is that let contents always end up as nil.

The structure from the location of the .xcodeproj file looks like this: EmojiBoard/emojis/emoji-0.png and so on.

I've been trying to use the NSFileManager with no luck.

let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath("emojis", error: &error)
println(contents)

This prints nil. I've also tried "EmojiBoard/emojis" and "/EmojiBoard/emojis".

I need this to determine how many images there are and loop them all out without having to resort to an insane switch statement or something like that.

Thank you!

P.S. Please note that I'm coding in Swift, not Objective C. I'm not proficient enough to convert C programming to swift I'm afraid. D.S.


Solution

  • if you created folder reference when adding the folder to your project use it like this (emojis folder icon is a blue folder):

    let resourceURL = Bundle.main.resourceURL!.appendingPathComponent("emojis")
    var resourcesContent: [URL] {
        (try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
    }
    let emojiCount = resourcesContent.count
    print(emojiCount)
    

    if you created groups when adding the folder to your project use it like this (emojis folder icon is a yellow folder):

    let resourceURL = Bundle.main.resourceURL!
    let resourcesContent = (try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
    let emojiCount = resourcesContent.filter { $0.lastPathComponent.hasPrefix("emoji-") }.count
    print(emojiCount)