当我在 swift 3 中从图库中获取照片时,为啥收藏视图为空?

Posted

技术标签:

【中文标题】当我在 swift 3 中从图库中获取照片时,为啥收藏视图为空?【英文标题】:why collection view in empty when I fetch photos from gallery in swift 3?当我在 swift 3 中从图库中获取照片时,为什么收藏视图为空? 【发布时间】:2017-06-03 06:27:24 【问题描述】:

我正在使用 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()
    



【问题讨论】:

将此行放在 for 循环结束 self.collectionImageView?.reloadData() 之后。获取所有图像后,您不会重新加载 collectionview。将此行放入 if fetchResult.count > 0 for 循环之后 我在收藏视图中仍然看不到任何照片 你会分享演示吗? 想象一下,白页没有任何东西,没有任何错误,这些是我的完整代码 等我给你演示 【参考方案1】:

这是我从画廊加载所有图像并加载到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
    


【讨论】:

你能在这里写集合视图单元格代码吗? 等我给你演示一下。 它正在工作,但在第一次启动时我看不到照片 它来自您的图库,如果有 1000 多张照片,则需要一些时间才能获取它 不,我在模拟器中测试过这个,模拟器只有5张照片【参考方案2】:

你必须像这样在你的 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()


    ...

【讨论】:

我再也看不到照片了

以上是关于当我在 swift 3 中从图库中获取照片时,为啥收藏视图为空?的主要内容,如果未能解决你的问题,请参考以下文章

当我在 Swift 中从音乐库中选择歌曲时,为啥我的应用程序会崩溃?

swift 3中的按钮背景图像

如何从手机图库中获取照片?

如何在 swift 4 中从图像选择器获取照片本地 url

如何在 IONIC 3 中从图库中获取或选择图像

XC测试。检测访问图库警报视图