ios - 在 UICollectionView 中加载用户相册时内存增长失控

标签 ios swift uicollectionview phasset photosframework

我正在将用户相册中的照片加载到 Collection View 中,类似于 this Apple Sample project 中的操作。 .我似乎无法追查为什么内存增长失控。我使用建议的 PHCachingImageManager但所有这些结果都是图像模糊、滚动卡住和内存增长失控,直到应用程序崩溃。

在我的 viewDidLoad 中,我运行下面的代码

        PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) in
            print("photo authorization status: \(status)")
            if status == .authorized && self.fetchResult == nil {
                print("authorized")

                let fetchOptions = PHFetchOptions()
                fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
                var tempArr:[PHAsset] = []
                self.fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

                guard let fetchResult = self.fetchResult else{
                    print("Fetch result is empty")
                    return
                }

                fetchResult.enumerateObjects({asset, index, stop in
                    tempArr.append(asset)
                })
//                self.assets = tempArr

                self.imageManager.startCachingImages(for: tempArr, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil)

                tempArr.removeAll()
                print("Asset count after initial fetch: \(self.assets?.count)")

                DispatchQueue.main.async {
                    // Reload collection view once we've determined our Photos permissions.
                    print("inside of main queue reload")
                    PHPhotoLibrary.shared().register(self)
                    self.collectionView.delegate = self
                    self.collectionView.dataSource = self
                    self.collectionView.reloadData()
                }
            } else {
                print("photo access denied")
                self.displayPhotoAccessDeniedAlert()
            }
        }

cellForItemAt: 内部,我运行以下代码

cellForItemAt

  guard let fetchResult = self.fetchResult else{
            print("Fetch Result is empty")
            return UICollectionViewCell()
        }

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false
        requestOptions.deliveryMode = .highQualityFormat
        //let scale = min(2.0, UIScreen.main.scale)
        let scale = UIScreen.main.scale
        let targetSize = CGSize(width: cell.bounds.width * scale, height: cell.bounds.height * scale)

//        let asset = assets[indexPath.item]
        let asset = fetchResult.object(at: indexPath.item)
        let assetIdentifier = asset.localIdentifier

        cell.representedAssetIdentifier = assetIdentifier

        imageManager.requestImage(for: asset, targetSize: cell.frame.size,
                                              contentMode: .aspectFill, options: requestOptions) { (image, hashable)  in
                                                if let loadedImage = image, let cellIdentifier = cell.representedAssetIdentifier {

                                                    // Verify that the cell still has the same asset identifier,
                                                    // so the image in a reused cell is not overwritten.
                                                    if cellIdentifier == assetIdentifier {
                                                        cell.imageView.image = loadedImage
                                                    }
                                                }
        }

最佳答案

本周我在使用 Apple 代码时遇到了类似的问题,其他人可以在此处获得引用 Browsing & Modifying Photos

内存使用率非常高,然后如果查看单个项目并返回根目录,内存会激增并且示例会崩溃。

因此,根据我们的实验,有一些改进性能的调整。

首先在为requestImage函数设置thumbnailSize时:

open func requestImage(for asset: PHAsset, targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID

我们像这样设置比例而不是使用完整尺寸:

UIScreen.main.scale * 0.75

我们还将 PHImageRequestOptions Resizing Mode 设置为 .fast

除此之外,我们发现设置 CollectionViewCell 的以下变量也有所帮助:

layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isOpaque = true

我们还注意到 ScrollViewwDidScroll 方法中的 updateCachedAssets() 在此过程中发挥了一定作用,因此我们将其从回调中删除(正确或错误)。

最后一件事是我们为每个单元保留对 PHCachingImageManager 的引用,如果它存在,那么我们调用:

open func cancelImageRequest(_ requestID: PHImageRequestID)

因此,这是我们的 MediaCell 的代码:

extension MediaCell{

  /// Populates The Cell From The PHAsset Data
  ///
  /// - Parameter asset: PHAsset
  func populateCellFrom(_ asset: PHAsset){

    livePhotoBadgeImage = asset.mediaSubtypes.contains(.photoLive) ? PHLivePhotoView.livePhotoBadgeImage(options: .overContent) : nil

    videoDuration = asset.mediaType == .video ? asset.duration.formattedString() : ""

    representedAssetIdentifier = asset.localIdentifier
  }


  /// Shows The Activity Indicator When Downloading From The Cloud
  func startAnimator(){
    DispatchQueue.main.async {
      self.activityIndicator.isHidden = false
      self.activityIndicator.startAnimating()
    }
  }


  /// Hides The Activity Indicator After The ICloud Asset Has Downloaded
  func endAnimator(){
    DispatchQueue.main.async {
      self.activityIndicator.isHidden = true
      self.activityIndicator.stopAnimating()
    }
  }

}

final class MediaCell: UICollectionViewCell, Animatable {

  @IBOutlet private weak var imageView: UIImageView!
  @IBOutlet private weak var livePhotoBadgeImageView: UIImageView!
  @IBOutlet private weak var videoDurationLabel: UILabel!
  @IBOutlet weak var activityIndicator: UIActivityIndicatorView!{
    didSet{
      activityIndicator.isHidden = true
    }
  }

  var representedAssetIdentifier: String!
  var requestIdentifier: PHImageRequestID!

  var thumbnailImage: UIImage! {
    didSet {
      imageView.image = thumbnailImage
    }
  }

  var livePhotoBadgeImage: UIImage! {
    didSet {
      livePhotoBadgeImageView.image = livePhotoBadgeImage
    }
  }

  var videoDuration: String!{
    didSet{
     videoDurationLabel.text = videoDuration
    }
  }

  //----------------
  //MARK:- LifeCycle
  //----------------

  override func awakeFromNib() {
    layer.shouldRasterize = true
    layer.rasterizationScale = UIScreen.main.scale
    isOpaque = true
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    imageView.image = nil
    representedAssetIdentifier = ""
    requestIdentifier = nil
    livePhotoBadgeImageView.image = nil
    videoDuration = ""
    activityIndicator.isHidden = true
    activityIndicator.stopAnimating()
  }

}

cellForItem 的代码:

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let asset = dataViewModel.assettAtIndexPath(indexPath)

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mediaCell", for: indexPath) as! MediaCell

    if let requestID = cell.requestIdentifier { imageManager.cancelImageRequest(requestID) }

    cell.populateCellFrom(asset)

    let options = PHImageRequestOptions()
    options.resizeMode = .fast
    options.isNetworkAccessAllowed = true

    options.progressHandler = { (progress, error, stop, info) in

      if progress == 0.0{
        cell.startAnimator()
      } else if progress == 1.0{
        cell.endAnimator()
      }
    }

    cell.requestIdentifier = imageManager.requestImage(for: asset, targetSize: thumbnailSize,
                                                       contentMode: .aspectFill, options: options,
                                                       resultHandler: { image, info in

                                                        if cell.representedAssetIdentifier == asset.localIdentifier {

                                                          cell.thumbnailImage = image


                                                        }

    })

    return cell
  }

另一个区域在 updateCachedAssets() 函数中。您正在使用:

self.imageManager.startCachingImages(for: tempArr, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil)

最好在此处设置较小的尺寸,例如:

imageManager.startCachingImages(for: addedAssets,
                                targetSize: thumbnailSize, contentMode: .aspectFill, options: nil)

因此缩略图大小例如:

/// Sets The Thumnail Image Size
private func setupThumbnailSize(){

let scale = isIpad ? UIScreen.main.scale : UIScreen.main.scale * 0.75
let cellSize = collectionViewFlowLayout.itemSize
thumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale)

}

所有这些调整都有助于确保内存使用量保持公平不变,并且在我们的测试中确保没有抛出异常。

希望对您有所帮助。

关于ios - 在 UICollectionView 中加载用户相册时内存增长失控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58106814/

相关文章:

ios - RxSwift 将 Observable<Bool> 转换为 Observable<Void>

ios - 无法从 Spritekit SKScene 到另一个 UIViewController,XCODE8/Swift

ios - 在 iOS 中打开应用程序后呈现 View Controller 的确定方式是什么?

ios - 第一次加载时自动选择项目

iphone - UICollectionView 图像之间的空间

ios - 使用 spritekit 和 UITouch 绘制直线创建多条线

iphone - 使用 SBJSON 进行 JSON 解析和检查

swift - swift3中NSNumber怎么写?

ios - 未显示自定义 UIViewController 的 View

ios - 滚动后自定义 UICollectionView 单元格 layoutsubview 不正确