目标
操纵几个高分辨率的本地图像而不捕捉它们,然后在集合视图中选择并显示其中一些图像。
限制
PHImageManager没有选项可以在不捕获本地图像的情况下检索本地图像。 PHAsset没有指定其本地路径的属性。最后,我不可能使用UIImage或NSData对象的数组,因为它很快达到内存限制并崩溃。
工具
Xcode 8.1 - Swift 3.0.1
现状
首先,我获取资产,然后遍历它们以获取其本地路径。获取本地路径的原因是访问它们而不使用UIImage(contentsOfFile: localPath)
或UIImage.init(data: Data(contentsOf: localPath))
来捕获它们。然后,我在图像上运行一些业务逻辑,然后选择其中一些。最后,我将所选图像的本地路径存储在一个数组中,然后由集合视图使用。
注意:在iOS 10或更高版本中,requestContentEditingInput
completion handler在主队列上调用。
问题
一切正常,直到集合视图尝试加载本地图像。使用UIImage(contentsOfFile: localPath)
完成处理程序内的requestContentEditingInput
成功加载图像的本地路径。但是,在集合视图函数collectionView(_ collectionView:, cellForItemAt indexPath:)
内使用相同的函数加载时,同一图像的本地路径会带来nil
。
因此,我想知道我错过了什么或做错了什么。我已经尝试使用资产cancelContentEditingInputRequest
,认为图像上可能存在某种类型的锁定,但它没有解决问题。
代码示例
var imagesSelected = [String]()
@IBOutlet weak var imageCollectionView: UICollectionView!
private func processImages() {
...
assets.enumerateObjects({ (asset, count, stop) in
...
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions(), completionHandler: { (input, _) in
if let url = input?.fullSizeImageURL {
if let image = UIImage(contentsOfFile: url.relativePath) {
...
if (...) {
self. imagesSelected.append(url.relativePath)
self.imageCollectionView.reloadData()
}
}
}
})
})
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath as IndexPath) as! ImageCollectionViewCell
cell.productImage.image = UIImage(contentsOfFile: self.images[indexPath.row])
return cell;
}