Swift: How to extract image filename from an array of UIImage

10,793

Solution 1

I have had a look around as this has been a problem for me in the past also. UIImage does not store the filename of the image. What I did to solve the issue was instead of an image array I used a dictionary with the key as the filename and the value as the Image. In my for loop I extracted the key and value of each item into a tuple and dealt with them.

I no longer have the code but as a quick mock up of what I did see below, (I hope this fits your requirements as I know every application is different)

var imageDictionary = ["image1.png": UIImage(named: "image1.png"),
     "image2.png": UIImage(named: "image2.png")]

and then the for loop will look like:

for (key, value) in imageDictionary {
    println(key) // Deal with Key
    println(value) // Deal with Value
}

...as I say this worked for me and the scenario I needed it for, I hope you can use it also!

Good luck!

Solution 2

Once you create the instance of the UIImage, all references to the name are lost. For example, when you make an image from a file, you do something like this:

var image: UIImage = UIImage(named: "image.png")

After that's done, there are no more references to the file name. All of the data is stored in the UIImage instance, regardless of where it came from. As the comments said above, you'll need to devise a way to store the names if you must do so.

Share:
10,793
ADRSPR
Author by

ADRSPR

Updated on June 04, 2022

Comments

  • ADRSPR
    ADRSPR almost 2 years

    If I have an array of UIImage like so:

    newImageArray = [UIImage(named:"Red.png")!,
            UIImage(named:"Green.png")!,
            UIImage(named:"Blue.png")!, UIImage(named:"Yellow.png")!]
    

    How can I extract or determine the filename of an image of a certain index later on? For example:

    println("The first image is \(newImageArray[0])")
    

    Instead of returning a readable filename, it returns:

    The first image is <UIImage: 0x7fe211d2b1a0>
    

    Can I convert this output into readable text, or is there a different method of extracting filenames from UIImage arrays?