0

I have been going through many Swift and Objective-C posts over several hours to help me create a function that returns an array of the string filenames of a directory in xcassets. I then can use the array of filenames to create another function that displays a random image to my user.

var imageDirectory  = [String]()


func getContentOfImageDirectory() -> [String] {

    imageDirectory.removeAll(keepCapacity: false)


    let fm = NSFileManager.defaultManager()

    let sourcePath = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("DeviceImagesFolder")

    var tempArray = fm.contentsOfDirectoryAtPath(sourcePath, error: nil)


    if tempArray != nil {

        self.imageDirectory = tempArray as! [String]

        return imageDirectory

    }

    else {
        println("tempArray was nil")


        if fm.fileExistsAtPath(sourcePath){

            println("There is a file")
            return []
        }

        else {
            println("There is not a file")
            return []
        }
    }

}

However tempArray keeps returning nil and "There is not a file". And obviously my function returns the entire contains of "DeviceImagesFolder", rather than an array of the filenames.

If anyone could offer a solution to this problem it would be very much appreciated. Cheers.

  • http://stackoverflow.com/questions/19346394/can-i-programmatically-list-files-in-images-xcassets-something. Try to save an array of image names and get image name randomly from array. – johny kumar Jul 06 '15 at 06:49
  • But how would I get an array of image names, without manually typing in the filename of each image into the array? – user2176152 Jul 07 '15 at 01:52

1 Answers1

0

Xcode compiles the files inside the xcassets folder into one file (named "Assets.car").

So instead of using xcassets, you should just add the files inside a "normal" folder. Make sure to have them copied in the "Copy Bundle Resources" build phase.

freytag
  • 4,769
  • 2
  • 27
  • 32
  • First off, thanks for the reply. I have done as you advised, and when I added the "normal" folder of images xcode automatically added the images in the folder into the "Copy Bundle Resources" itself (but not the actual folder itself) I then run the code and I still get "tempArray was nil" and "There is not a file". Do you have any other tips? – user2176152 Jul 07 '15 at 01:49
  • 1
    When you add the folder to Xcode, make sure to add it as "folder reference", not as a group. The folder should then appear in blue in the project navigator. It should also appear as a folder in the "Copy Bundle Resources" step. – freytag Jul 07 '15 at 09:14