我正在努力解决从 iPhone 显示照片库到 collectionView
的问题。
如果有人的图库里有50张照片,一切都运作良好。但是当某人有数千张照片时,图库会加载10秒钟,这对我的应用程序不好。
当我从 Facebook 加载图像时也会出现同样的问题。应用程序等待直到下载完每张照片,然后才显示它们。我想在加载操作期间逐个显示图像,而不是等待所有图像都加载完成。
我知道我应该使用 DispatchQueue
,我已经使用了,但是有一些我看不到的错误。
这是我用于从 iPhone 图库获取图像的代码:
func grapPhotos() {
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResulat : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {
if fetchResulat.count > 0 {
for i in 0..<fetchResulat.count {
imgManager.requestImage(for: fetchResulat.object(at: i), targetSize: CGSize(width: 200, height:200), contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: {
(image, eror) in
self.imageArray.append(image!)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
})
}
} else {
print("You have no photos")
self.collectionView.reloadData()
}
}
}
以下是在 collectionView
中展示它们的代码:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "galleryCell", for: indexPath) as! GalleryCollectionViewCell
let image = self.imageArray[indexPath.row]
DispatchQueue.main.async {
cell.gelleryImages.image = image
}
return cell
}
可能我 Facebook 类的问题也是一样的,所以非常感谢您的帮助。
.fastFormat
,但它仍需要一些时间来加载。如果它可以逐个显示图像,那就太棒了。不是全部一起,而是在准备好时一个接一个地显示。 - Matt199requestImageData
中一次只获取一个资产,对吗? - Matt199