我正在尝试使用调度背景在集合视图中使用本地标识符获取资产,但加载时间过长且单元格为空

Posted

技术标签:

【中文标题】我正在尝试使用调度背景在集合视图中使用本地标识符获取资产,但加载时间过长且单元格为空【英文标题】:I am trying to fetch asset using local identifier in collection view using dispatch background but it takes too much time to load and cell are empty 【发布时间】:2017-07-27 09:23:48 【问题描述】:

我正在尝试使用从单元格中的本地标识符获取资产来从本地标识符加载资产 在后台线程的 indexpath 中并在集合视图单元格中显示它,但加载时间太长,单元格为零。有数百张图像。这里是代码。

这种方法对于在 cellfor indexpath 中获取资产是否正确?

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

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

cell.representedAssetIdentifier = "localidentifier"

    DispatchQueue.main.async() 
                if let cachedImage = self.imageCache.object(forKey: localidentifier! as NSString) as? UIImage 
                    cell.image  = cachedImage

                
            

            //let asset = self.assetsByDate[indexPath.section].1[indexPath.row]
            DispatchQueue.global(qos: .background).async 
                 let asset = PHAsset.fetchAssets(withLocalIdentifiers: [localidentifier!], options: .none).firstObject
                let mystring  = String(describing: asset)
                //print("the asset to string \(mystring)")
               // print ("String to asset \( mystring as! PHAsset)")


                self.imageManager.requestImage(for:  asset!, targetSize: self.thumbnailSize, contentMode: .aspectFit, options: PHImageRequestOptions(), resultHandler:  result, info in
                    if cell.representedAssetIdentifier =="localidentifier" 
                        DispatchQueue.main.async() 

                            DispatchQueue.main.async() 


                                if let image = result 
                                    self.imageCache.setObject(image, forKey:localidentifier!  as NSString)
                                    cell.image= image
                                

                            
                        

                    
                )

            

【问题讨论】:

【参考方案1】:

即使您在后台线程中加载图像(这是一个好点),单元格也不应该为零。所以我认为问题并不完全存在。

在您的情况下,即使图像仍在加载,该方法也应返回带有 ImageView 的单元格。 然后,当加载结束时,它应该在 imageView 中显示图像。

问题也可能来自关于主线程的重复行:

DispatchQueue.main.async() 
    DispatchQueue.main.async() 

您应该删除其中一个。 您还必须使用弱引用来避免 nil 异常或泄漏:

DispatchQueue.main.async()  [weak self] in
    if let image = result 
        self.imageCache.setObject(image, forKey:localidentifier!  as NSString)
    cell.image= image
    

【讨论】:

我试过了,但如果我向上滚动某些单元格的图像变空,仍然需要很长时间才能加载 嗨 maxime 你有空吗? 这种方法对于从单元格中的本地标识符中为 indexpath 中的项目获取图像是否正确?? 你确定这只是延迟问题。您确定加载结束时图像不为零吗? 在准备重用时,我将 imageview 设为 nil image.image = nil super.prepareForReuse() 但如果我不使用,单元格会重复以前的图像

以上是关于我正在尝试使用调度背景在集合视图中使用本地标识符获取资产,但加载时间过长且单元格为空的主要内容,如果未能解决你的问题,请参考以下文章

如何正确使用带有本地标识符的获取资产?

无法更新本地预定通知内容

UICollectionView 固定背景视图

如何在 Xamarin 表单中使用 MVVM 仅为集合视图中的选定框架设置颜色?

带有标识符的背景 URLSession 的问题

集合视图自动调整大小和设置重复背景