首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UICollecitonView中加载用户相册时内存增长失控

在UICollecitonView中加载用户相册时内存增长失控
EN

Stack Overflow用户
提问于 2019-09-25 21:33:50
回答 1查看 886关注 0票数 0

我正在将用户相册中的照片加载到类似于这个苹果样例项目的集合视图中。我似乎找不出为什么记忆会失控。我使用建议的PHCachingImageManager,但所有的结果都是模糊的图像,冻结滚动和内存增长失控,直到应用程序崩溃。

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

代码语言:javascript
复制
        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

代码语言:javascript
复制
  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
                                                    }
                                                }
        }
EN

回答 1

Stack Overflow用户

发布于 2019-09-25 23:53:55

本周,我遇到了一个类似的问题,使用Apple,对于其他人来说,它可以在这里找到浏览和修改照片

内存使用率很高,如果查看单个项并返回根,内存就会激增,这个示例就会崩溃。

因此,从我们的实验中,有一些改进,提高了性能。

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

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

我们将刻度设置为这样,而不是使用完整的大小:

代码语言:javascript
复制
UIScreen.main.scale * 0.75

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

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

代码语言:javascript
复制
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isOpaque = true

我们还注意到,updateCachedAssets()方法中的ScrollViewwDidScroll在这个过程中扮演了一定的角色,因此我们从这个回调(正确或错误)中删除了它。

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

代码语言:javascript
复制
open func cancelImageRequest(_ requestID: PHImageRequestID)

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

代码语言:javascript
复制
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的代码

代码语言:javascript
复制
 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()函数中还有一个区域。您正在使用:

代码语言:javascript
复制
self.imageManager.startCachingImages(for: tempArr, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil)

最好在这里设置一个较小的尺寸,例如:

代码语言:javascript
复制
imageManager.startCachingImages(for: addedAssets,
                                targetSize: thumbnailSize, contentMode: .aspectFill, options: nil)

例如,缩略图大小:

代码语言:javascript
复制
/// 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)

}

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

希望能帮上忙。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58106814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档