iosswiftuiimageview

How to get a random image from a folder in swift?


So far I have created a folder of images and I am able to assign 1 of the images to a UIImageView.

But what I want to do now is create a random generator, that will pick a random image from the folder, so if I was to create a button, I could display all of the images separately and randomly on a single UIImageView.

However, this folder is going to have more than 100 images, so I don't want to hard code each one into an array. Also, the names of the image has to be unique to the image itself.

I have been searching online but cannot find information on how to code what will suit my needs. So how would I get and display a random image(s) from a folder in swift?


Solution

  • You can name your images like this

    image_0
    image_1
    image_2
    

    Then use this code to populate your UIImageView

    let numberOfImages: UInt32 = 100
    let random = arc4random_uniform(numberOfImages)
    let imageName = "image_\(random)"
    imageView.image = UIImage(named: imageName)
    

    Update

    Since you don't want to rename your images you can create a plist file (type Array) where you put all the names of your images

    enter image description here

    And finally

    func loadRandomImage() {
        let path = NSBundle.mainBundle().pathForResource("Images", ofType: "plist")!
        let names = NSArray(contentsOfFile: path) as! [String]
        let random = Int(arc4random_uniform(UInt32(names.count)))
        let imageName = names[random]
        imageView.image = UIImage(named: imageName)
    }