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

时间:2017-06-03 06:27:24

标签: ios swift3 uicollectionview photolibrary camera-roll

我正在使用swift 3并希望在集合视图中看到照片库IMAGES但这些代码对我不起作用

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

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


}

2 个答案:

答案 0 :(得分:3)

这是我的整个代码,用于从gallery中加载所有图像并加载到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
    }

}

答案 1 :(得分:0)

你必须在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()

}
    ...