Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array of UIImage, from folder, in Swift?

Tags:

ios

swift

uiimage

I have an ordinary Xcode project like this ...

enter image description here

notice there's a folder (it is an actual folder - not just a group) named "images". It contains 25 ".png" images.

All I want to do is make an array of UIimage with each of those images.

(Or even, an array of the image names or similar, that would be fine - then could load them UIImage(named:)

How do I get at that folder "images"?? What about a subfolder "images/cars"?

I tried something like this but it finds nothing...

override func viewDidLoad()
    {
    let imageArray = NSBundle.mainBundle().URLsForResourcesWithExtension(
          "png", subdirectory: "images")
    print("test...")
    for n:NSURL in imageArray!
        { print("found ..." ,n) }
    }
like image 507
Fattie Avatar asked May 23 '16 22:05

Fattie


4 Answers

We we assume the images are in the app's resource bundle. If not you need to make sure that your images directory is listed in the "Copy Bundle Resources" in the "Build Phases" of the target.

enter image description here

EDIT This is only going copy the images into the app bundle, if you require the folder to be copied to the app bundle per the code below then please use the follow StackOverflow question to set it up correctly.

This gives us an array of URL's that we can then use with UIImage(data:) and NSData(contentsOfURL:) to create the image when needed.

Get the bundle's resource path and append the image directory then get the contents of the directory.

     if let path = NSBundle.mainBundle().resourcePath {

        let imagePath = path + "/images"
        let url = NSURL(fileURLWithPath: imagePath)
        let fileManager = NSFileManager.defaultManager()

        let properties = [NSURLLocalizedNameKey,
                          NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]

        do {
            let imageURLs = try fileManager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)

            print("image URLs: \(imageURLs)")
            // Create image from URL
            var myImage =  UIImage(data: NSData(contentsOfURL: imageURLs[0])!)

        } catch let error1 as NSError {
            print(error1.description)
        }
    }
like image 79
Peter Hornsby Avatar answered Nov 19 '22 19:11

Peter Hornsby


You can follow these steps to download them:

  1. Create a new folder in finder and add all images (or folder, ... everything).

  2. Change folder name + ".bundle" (for example: YourListImage -> YourListImage.bundle).

  3. Add folder to project.

  4. Add FileManager extension:

    extension FileManager {
        func getListFileNameInBundle(bundlePath: String) -> [String] {
    
            let fileManager = FileManager.default
            let bundleURL = Bundle.main.bundleURL
            let assetURL = bundleURL.appendingPathComponent(bundlePath)
            do {
                let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
                return contents.map{$0.lastPathComponent}
            }
            catch {
                return []
            }
        }
    
        func getImageInBundle(bundlePath: String) -> UIImage? {
            let bundleURL = Bundle.main.bundleURL
            let assetURL = bundleURL.appendingPathComponent(bundlePath)
            return UIImage.init(contentsOfFile: assetURL.relativePath)
        }
    }
    
  5. Use:

     let fm = FileManager.default
     let listImageName = fm.getListFileNameInBundle(bundlePath: "YourListImage.bundle")
     for imgName in listImageName {
         let image = fm.getImageInBundle(bundlePath: "YourListImage.bundle/\(imgName)")
     }
    
like image 28
Ten Avatar answered Nov 19 '22 19:11

Ten


Please try the following:

enter image description here

  1. You have to register your images to "Copy Bundle Resources".

  2. You have to add filter module in main Bundle. enter image description here

It is working well on my side. Maybe you can change filter from "jpg" format into "png" one.

I've tested on iOS 10.x later, Swift 3.0 and xcode 8.1 version.

like image 5
Bogdan Dimitrov Filov Avatar answered Nov 19 '22 18:11

Bogdan Dimitrov Filov


I would advise against loading all of your images into an array at once. Images tend to be large and it's easy to run out of memory and crash.

Unless you absolutely have to have all the images in memory at once it's better to keep an array of paths or URLs and load the images one at a time as needed.

Assuming the folder full of images is in your app bundle, you can use the NSBundle method URLsForResourcesWithExtension:subdirectory: to get an array of NSURLs to all the files in your images subdirectory, either with a specific filetype, or ALL files (if you pass nil for the extension.)

Once you have an array of file urls you can map it to an array of paths if needed, and then map that to an array of images.

like image 4
Duncan C Avatar answered Nov 19 '22 17:11

Duncan C