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

前端 未结 5 1415
别跟我提以往
别跟我提以往 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: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)
            }
        }
    

提交回复
热议问题