【发布时间】:2019-09-25 21:33:50
【问题描述】:
我正在将用户相册中的照片加载到收藏视图中,类似于在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
}
}
}
【问题讨论】:
-
PHImageManagerMaximumSize的缓存似乎对内存不太友好。为什么细胞这么大? -
@WarrenBurton 我正在使用这个苹果示例项目中显示的马赛克网格布局developer.apple.com/documentation/uikit/uicollectionview/… 我想让照片加载,这样它们就不会模糊,所以我认为增大目标尺寸会有所帮助但事实并非如此。无论如何,我尝试将大小设置为屏幕宽度的 1/3,但内存问题似乎仍然存在。有什么想法吗?
-
问题解决了吗?
标签: ios swift uicollectionview phasset photosframework