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

前端 未结 5 1422
别跟我提以往
别跟我提以往 2021-02-13 19:18

I have an ordinary Xcode project like this ...

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

相关标签:
5条回答
  • 2021-02-13 19:41

    Joe.

    Please try as followings:

    My current situation was as follows. 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 as 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. If you have any problem, please contact me.

    0 讨论(0)
  • 2021-02-13 19:46

    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.

    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)
            }
        }
    
    0 讨论(0)
  • 2021-02-13 19:53

    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)")
       }
      
    0 讨论(0)
  • 2021-02-13 19:57

    Swift 4

        if let path = Bundle.main.resourcePath {
            let imagePath = path + "/images"
            let url = NSURL(fileURLWithPath: imagePath)
            let fileManager = FileManager.default
    
            let properties = [URLResourceKey.localizedNameKey,
                              URLResourceKey.creationDateKey, 
                              URLResourceKey.localizedTypeDescriptionKey]
    
            do {
                let imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
    
                print("image URLs: \(imageURLs)")
                // Create image from URL
                let firstImageURL = imageURLs[0]
                let firstImageData = try Data(contentsOf: firstImageURL)
                let firstImage = UIImage(data: firstImageData)
    
                // Do something with first image
    
            } catch let error as NSError {
                print(error.description)
            }
        }
    
    0 讨论(0)
  • 2021-02-13 20:08

    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.

    0 讨论(0)
提交回复
热议问题