【发布时间】:2016-11-02 15:31:07
【问题描述】:
我正在尝试使用照片框架提取用户库中的所有视频并将它们显示在集合视图中。基本上实现了我自己的视频选择器。
我正在使用 PHCachingImageManager 开始缓存每个视频的图像缩略图。当调用“cellForItemAt indexPath”时,当我调用 PHCachingImageManager.requestImage(...) 并尝试在闭包中设置我的单元格的图像时,我得到“在展开可选值时意外发现 nil”。
viewDidLoad() {
// Register Cell classes
self.collectionView!.register(PhotosCell.self, forCellWithReuseIdentifier: reuseIdentifier)
let videosAlbum = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumVideos, options: nil)
print(videosAlbum.count) // prints as 1 bc videosAlbum contains 1 collection
self.videos = PHAsset.fetchAssets(in: videosAlbum.object(at: 0), options: nil)
print(self.videos.count) // prints the # of videos in the Videos smart album
self.imageManager.startCachingImages(for: self.videos.objects(at: [0, videos.count-1]), targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFit, options: nil)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotosCell
let asset = videos.object(at: indexPath.item)
imageManager.requestImage(for: asset, targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFill, options: nil, resultHandler: {
image, _ in
cell.thumbnailImage = image //this is the line throwing the error
})
return cell
}
这可能是我实现 PhotosCell 类的方式的问题吗?还是我使用 'collectionView.dequeueReusableCell(...) 的方式有问题?
class PhotosCell: UICollectionViewCell {
@IBOutlet weak var photoThumbnail: UIImageView!
var thumbnailImage: UIImage! {
didSet {
photoThumbnail.image = thumbnailImage
}
}
}
我环顾四周,以为我看到了传递给缓存管理器的闭包放在后台线程上的位置,但这不应该影响在错误行上设置的可选 UIImageView.image,对吧? GitHub 代码是 here 以获得更多上下文。
【问题讨论】:
标签: ios swift photosframework