ios - PHImageManager 的 requestImage 在滚动数千张图像时锁定 UI

标签 ios swift multithreading uikit photosframework

我有一个 Collection View ,其中显示所有用户的照片。基本的东西,一个数据源,它获取 PHAssets 并在 PHCachingImageManager 上使用 requestImage 来加载缩略图。

但最近我收到一个错误报告,当您拥有超过 5000 张图像并快速滚动浏览图像时,UI 会卡住。经过调查,我能够重现该问题,并且似乎主线程在调用 requestImage 后立即被锁定(_lock_wait),而该调用创建的数十个其他线程(其他线程的缩略图)细胞)也被锁定等待谁知道什么。

我尝试了几种方法,但没有任何作用:

  1. 实现了 UICollectionViewDataSourcePrefetching,并使用 PHCachingImageManagerprefetchItemsAt 事件上启动CachingImages。有趣的是,它让事情变得更糟,因为它试图一次加载更多图像。而且 cancelPrefetchingForItemsAt 本来应该在单元格超出屏幕时调用,但从未被调用过。

  2. 尝试对较慢的请求调用 cancelImageRequest,但也没有成功。

现在我不知道还能做什么,我可以在后台dispatch_queue上运行requestImage,这样它就不会锁定我的主线程,但感觉很奇怪,因为该方法会生成另一个线程本身

我的代码是这样的:

let requestOptions = PHImageRequestOptions()
requestOptions.resizeMode = .fast
requestOptions.deliveryMode = .opportunistic
requestOptions.isSynchronous = false
requestOptions.isNetworkAccessAllowed = true
return requestOptions

myManager.requestImage(for: asset, targetSize: CGSize(width: 375, height: 375), contentMode: .aspectFill, options: options) { /* use image */ }

ps:我不确定,但似乎这只发生在 iOS 11 上,目前我只能在 iPhone X 上重现

最佳答案

事实证明这就是问题所在:GCD dispatch concurrent queue freeze with 'Dispatch Thread Soft Limit Reached: 64' in crash log

requestImage 继续创建新线程,直到达到调度线程限制并且 UI 在此 _lock_wait 上卡住

解决方案是设置requestOptions.isSynchronous = true,创建一个具有有限并发性的OperationQueue,并将图像获取作为作业添加到该队列上。

//somewhere like viewDidLoad
operationQueue.maxConcurrentOperationCount = 54

//when setting up the cells
operationQueue.addOperation { [weak self] in
      self?.cachingImageManager.requestImage(/* params...*/) { (image) in
            OperationQueue.main.addOperation {
               //use image
            }
      }
}

关于ios - PHImageManager 的 requestImage 在滚动数千张图像时锁定 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876364/

相关文章:

SwiftUI:如何在 macOS 应用程序中实现编辑菜单

c# - C# 中的条件变量

c++ - 使用 std::mutex、std::condition_variable 和 std::unique_lock

ios - 附加到 NSString 时的正确内存管理

html - 如何检索图像 url 的标题

ios - 制作自定义相机,在我的应用程序委托(delegate)中收到 "Thread 1: signal SIGBRT"错误

multithreading - Redis 有 decr if 功能吗

ios 自定义 UIButton 缩放 setImage 向下不起作用

objective-c - 如何在表格 View 中对齐数组中的文本?

ios - 如何使用 Swift 将 Data/NSData 转换为整数数组