Raghuram
Raghuram

Reputation: 1711

Load multiple image from directory using swift

I am new to iOS swift programming really need help!

I downloaded images from url and saved to the path /Users/mymac/Library/Developer/CoreSimulator/Devices/583C02D5-9A88-4756-9044-CD6DB4DCB57C/data/Containers/Data/Application/699F623B-000B-4365-B451-CA3104AD958B/Documents/Images

Now i am able load images ImageView by specifying the name manually

    var fileName = "Images/1A_Dorsal aspect.jpg"
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    var getImagePath = paths.stringByAppendingPathComponent(fileName)
    imageLoad.image = UIImage(contentsOfFile: getImagePath)

what i need is load the image using the number (i.e 25 images are in my folder Images) using for loop i want to load the images one by one like Android(Java)

Upvotes: 2

Views: 4040

Answers (2)

Harjot Singh
Harjot Singh

Reputation: 6927

Load multiple images from the folder or directory. - Swift 4

Here's the image attached to show, what we want to achieve in the given below code. enter image description here

Here's the code to find the multiple images from the folder in documents directory. I have written one method to do the same.

In the code we are passing the "Folder Name" (ie. Red) and getting the contents of that directory. In return we got the array of images name.

static func loadImagesFromAlbum(folderName:String) -> [String]{

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
    let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    var theItems = [String]()
    if let dirPath          = paths.first
    {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(folderName)

        do {
            theItems = try FileManager.default.contentsOfDirectory(atPath: imageURL.path)
            return theItems
        } catch let error as NSError {
            print(error.localizedDescription)
            return theItems
        }
    }
    return theItems
}

Here's the result of given code. enter image description here

Hope it helps.

Thanks

Upvotes: 1

Mitul Marsoniya
Mitul Marsoniya

Reputation: 5299

Here you get all images name which store in "Images" folder Try bellow code:

 let fileManager = NSFileManager.defaultManager()
 let arrImages : NSMutableArray = []
            let tempFolderPath = AppHelper.fileInDocumentsDirectory("Images")
            do {
                let filePaths = try fileManager.contentsOfDirectoryAtPath(tempFolderPath)
                for filePath in filePaths {
                        try arrImages.addObject(tempFolderPath + "/" + filePath)

                }
            } catch {
                print("Could not get folder: \(error)")
            }
print(arrImages)

Upvotes: 0

Related Questions