gpt4 book ai didi

arrays - 从数组中删除重复的 PHAssets?

转载 作者:行者123 更新时间:2023-11-28 14:25:55 25 4
gpt4 key购买 nike

我正在使用名为 BSImagePicker 的第三方库从照片库中选择多张图像。我可以设置要选择的最大 PHAssets,但是当我显示 BSImagePickerController 以选择更多照片时,问题就来了。这些 PHAssets 只是另外添加到 selectedAssets 并且实际上复制了图像。我尝试删除重复的 PHAsset 和使用的图像,但它不起作用:

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(除了慢得无法忍受!)只是假设 PHAsset 相等性是重复图像的标记。它不是。 Assets 只是图书馆中内容的临时代表。您想要知道的是 Assets 的本地标识符是否与您已有的 Assets 匹配。我建议这样做:

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)
}
}

我们列出了我们已有 Assets 的所有本地标识符。然后,仅当其标识符不在列表中时,我们才附加 Assets (及其标识符)。这将快(因为 Set contains 比 Array contains 快得多),并且还应该防止“同一张照片”出现两次.

关于arrays - 从数组中删除重复的 PHAssets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51571137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com