为什么 collection 当我从 swift 3 中的图库中获取照片时,视图是空的?

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

我正在使用 swift 3 并希望在 collection 视图中查看照片库图像但是这些代码对我不起作用

在看到我的代码之前请注意: **我不会收到任何错误或崩溃我只是在 collection 视图中看不到我的任何图像库 ** 这是我的代码:

  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()
    }


}

您必须像这样在 for 循环后重新加载 collectionView

  ...
{
    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!)
                })
    self.collectionImageView?.reloadData()

}
    ...

这是我从图库加载所有图像并加载到 collectioview 的全部代码。请看这段代码

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
    }

}