Search code examples
iosswiftuiimagealassetslibrary

Is it possible to count pictures in asset catalog with particular prefix?


Is it possible to count pictures with particular prefix in asset catalog ? For exampe, I have images like:

Cocktail_01

Cocktail_02

...

Cocktail_nn

and other similar groups.

When my app starts, I do code like below:

var rec_cocktail = [UIImage]()
    for i in 1..<32 {
        if i < 10 {
            let name: String = "Cocktail__0" + i.description
            rec_cocktail.append(UIImage(named: name)!)
        } else {
            let name: String = "Cocktail__" + i.description
            rec_cocktail.append(UIImage(named: name)!)
        }
    }
    alcoholImages.append(rec_cocktail)

It's works perfect, but I have few groups to load and each one has different number of images. I have to check and change range each time when I add or remove picture from asset catalog.


Solution

  • It might be easier to use folders instead of Images.xcassets. Create a hierarchy you like on your computer and drag this into your Xcode project. Make sure you select:

    Create folder references for any added folders

    Then because you now have folder references when building your app you can iterate over items inside those folders using a loop.

    For example I dragged in a folder called "Cocktail" and created the reference. Now i can iterate over the items inside this folder using:

    let resourcePath = NSURL(string: NSBundle.mainBundle().resourcePath!)?.URLByAppendingPathComponent("Cocktail")
    let resourcesContent = try! NSFileManager().contentsOfDirectoryAtURL(resourcePath!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)
    
    for url in resourcesContent {
        print(url)
        print(url.lastPathComponent)
        print(url.pathExtension!) // Optional
    
    }
    

    The url.lastPathComponent is the filename of the image (e.g. Cocktail_01.jpeg) and the url itself is the complete path of the image.

    If you maintain a structure of folders it is very easy to iterate over them, if you want all the images in the same folder than you can create an array with just the image names you need and iterate over that using:

    // The Array of Image names
    var cocktailImagesArray : [String] = []
    
    // Add images to the array in the 'for url in resourceContent' loop
    if (url.lastPathComponent?.containsString("Cocktail")) {
        self.cocktailImagesArray.append(url.lastPathComponent)
    }
    

    This way you have all the images which contain Cocktail and have added them to your array. Now you can simple iterate over your freshly created array using:

    for imageName in self.cocktailImagesArray {
        // Do something
    }