Search code examples
iosswift3uicollectionviewphotolibrarycamera-roll

why collection view in empty when I fetch photos from gallery in swift 3?


I am Using swift 3 and want to see photo library IMAGES in the collection view But these codes doesn't work for me

before seeing my codes Attention to this : **I will not receive any errors or crash I just can't see any of my image library in the collection view ** here is my codes :

  import UIKit
  import Photos

 class collectionImageViewController: UIViewController , UICollectionViewDataSource , UICollectionViewDelegate {

var imageArray = [UIImage]()

@IBOutlet weak var collectionImageView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}



func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewImageCell", for: indexPath) as! CollectionViewImageCell

    cell.theImage.image = imageArray[indexPath.row]

    return cell
}

func getPhotosFromAlbum() {

    let imageManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

    if fetchResult.count > 0 {

        for i in 0..<fetchResult.count {

            imageManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: requestOptions, resultHandler: { image, error in

                self.imageArray.append(image!)
            })
        }
    } else {
        self.collectionImageView?.reloadData()
    }


}

Solution

  • This is my whole code to load all images from gallery and load into collectioview. Please see this code

    import UIKit
    import Photos
    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
        let arr_img = NSMutableArray()
        @IBOutlet var collview: UICollectionView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
            allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
            let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
            allPhotosResult.enumerateObjects({ (asset, idx, stop) in
    
                self.arr_img.add(asset)
            })
    
        }
        func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
            let retinaScale = UIScreen.main.scale
            let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
            let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
            let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
            let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))
    
            let manager = PHImageManager.default()
            let options = PHImageRequestOptions()
            var thumbnail = UIImage()
    
            options.isSynchronous = true
            options.deliveryMode = .highQualityFormat
            options.resizeMode = .exact
            options.normalizedCropRect = cropRect
    
            manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
                thumbnail = result!
            })
            return thumbnail
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        //MARK:
        //MARK: Collectioview methods
        func collectionView(_ collectionView: UICollectionView,
                            numberOfItemsInSection section: Int) -> Int {
            return arr_img.count
        }
        func collectionView(_ collectionView: UICollectionView,
                            cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                          for: indexPath)
            let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
            imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)
    
            return cell
        }
    
    }