我正在使用名为BSImagePicker的第三方库从照片库中选择多个图像。我可以设置最大的PHAssets
,但是当我显示“cc>”以选择更多照片时,问题就出现了。那些BSImagePickerController
只是添加到PHAssets
中,实际上是复制图像。我试图使用删除重复的selectedAssets
和图像,但它不起作用:
extension Array where Element: Equatable {
mutating func removeDuplicates() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
}
func presentBSImagePickerController(vc: BSImagePickerViewController) {
self.bs_presentImagePickerController(vc, animated: true,
select: { (asset: PHAsset) -> Void in
}, deselect: { (asset: PHAsset) -> Void in
// User deselected an assets.
}, cancel: { (assets: [PHAsset]) -> Void in
// User cancelled. And this where the assets currently selected.
}, finish: { (assets: [PHAsset]) -> Void in
// User finished with these assets
for i in 0..<assets.count {
self.selectedAssets.append(assets[i])
}
self.selectedAssets.removeDuplicates()
self.convertAssetToImages()
}, completion: nil)
}
func convertAssetToImages() -> Void {
if selectedAssets.count != 0 {
for i in 0..<selectedAssets.count {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: selectedAssets[i], targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
let data = UIImageJPEGRepresentation(thumbnail, 0.7)
let newImage = UIImage(data: data!)
self.photosArray.append(newImage! as UIImage)
self.photosArray.removeDuplicates()
print(self.photosArray.removeDuplicates())
DispatchQueue.main.async {
self.collectionView.reloadData() // reloads the collection view on main thread
}
}
}
}
最佳答案
问题在于
for i in 0..<assets.count {
self.selectedAssets.append(assets[i])
}
self.selectedAssets.removeDuplicates()
…那是你的
removeDuplicates
(除了速度太慢!)简单假设相位集相等是复制图像的标记。不是。资产只是图书馆里东西的临时代表。您想知道的是资产的本地标识符是否与您已经拥有的本地标识符匹配。我建议:var ids = Set(self.selectedAssets.map {$0.localIdentifier})
for asset in assets {
if !ids.contains(asset.localIdentifier) {
ids.insert(asset.localIdentifier)
self.selectedAssets.append(asset)
}
}
我们列出了我们已经拥有的资产的所有本地标识符。然后,仅当资产的标识符不在列表中时,我们才追加该资产(及其标识符)。这将快得多(因为Set
contains
比Arraycontains
快得多),而且还应该防止“同一张照片”出现两次。