Kanwal Hanjra
Kanwal Hanjra

Reputation: 201

How to show images within folder using collection view in swift

I am working on UICollectionView fetching gallery images and shown in UICollectionViewCell but i need to shown all images within one single folder.

Is there any solution for this?

Upvotes: 2

Views: 697

Answers (2)

Virani Vivek
Virani Vivek

Reputation: 896

You can try this way.Below code is fetch the "Repost" folder from gallery and fetch all the photos of it.

 func getImages() {

    image = []
    let albumName = "Repost" //album name
    let fetchOptions = PHFetchOptions()

    var assetCollection = PHAssetCollection()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let _:AnyObject = collection.firstObject{
        //found the album
        assetCollection = collection.firstObject!
        albumFound = true
    }
    else { albumFound = false
        print("album not found")
    }

    let assets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>

    assets.enumerateObjects({ (object, count, stop) in
        // self.cameraAssets.add(object)
        if object.mediaType == .image
        {
            self.image.append(object as! PHAsset) // for image
        }
    })

    self.image.reverse()
    self.imgcollection.reloadData()
}

Don't forgot to import photos framework. Thanks.

Upvotes: 1

Aamer Shahzad
Aamer Shahzad

Reputation: 13

In case you are still struggling to figure out here is the code snippet, good luck

func saveImageToDocumentDirectory(image: UIImage ) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileName = "image001.png" // name of the image to be saved
    let fileURL = documentsDirectory.appendingPathComponent(fileName)

    if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try data.write(to: fileURL)
            print("file saved")
        } catch {
            print("error saving file:", error)
        }
    }
}

func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)

    if let dirPath = paths.first {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
        let image    = UIImage(contentsOfFile: imageURL.path)
        return image!
    }
    return UIImage.init(named: "default.png")!
}

Upvotes: 0

Related Questions