swift 如何一次删除多个 PHAsset

Posted

技术标签:

【中文标题】swift 如何一次删除多个 PHAsset【英文标题】:swift How to delete multiple PHAssets at once 【发布时间】:2021-02-07 07:18:56 【问题描述】:

我想立即删除 PHAsset。我写了下面的代码,但是删除了,但是出现了选择alerts数量的问题。警报不能只出现一次吗?

     @IBAction func deleteBtnAction(_ sender: Any) 
    for (key, value) in dictionarySelectedIndexPath 
        if value 
            deletedNeededIndexPath.append(key)
        
    
    for i in deletedNeededIndexPath.sorted(by:  $0.item > $1.item) 
        sortedAlbum(true)
        guard let asset : PHAsset = self.fetchReuslt?.object(at: i.item) else  return 
        let assetArray : NSArray = [asset]
        phphotoLibrary.shared().performChanges(PHAssetChangeRequest.deleteAssets(assetArray), completionHandler: nil)
    
    AssetCollectionView.deleteItems(at: deletedNeededIndexPath)
    

我认为是因为for in。所以我重写如下,但是消息[PhotoKit] No photos access scope requirements declared for changes 出来了。这是为什么呢?

@IBAction func deleteBtnAction(_ sender: Any) 
    for (key, value) in dictionarySelectedIndexPath 
        if value 
            deletedNeededIndexPath.append(key)
        
    
    
    var assetArray : NSArray = []
    
    for i in deletedNeededIndexPath.sorted(by:  $0.item > $1.item) 
        sortedAlbum(true)
        guard let asset : PHAsset = self.fetchReuslt?.object(at: i.item) else  return 
        assetArray.addingObjects(from: [asset])

    

    PHPhotoLibrary.shared().performChanges(PHAssetChangeRequest.deleteAssets(assetArray), completionHandler: nil)
    AssetCollectionView.deleteItems(at: deletedNeededIndexPath)
    

【问题讨论】:

【参考方案1】:

我这样修复了我的代码:

let assetArray : NSMutableArray = NSMutableArray()
    
    for i in deletedNeededIndexPath.sorted(by:  $0.item > $1.item) 
        guard let asset : PHAsset = self.fetchReuslt?.object(at: i.item) else  return 
        assetArray.addObjects(from: [asset])
        

    PHPhotoLibrary.shared().performChanges(PHAssetChangeRequest.deleteAssets(assetArray), completionHandler: nil)
    AssetCollectionView.deleteItems(at: deletedNeededIndexPath)

这很好用

【讨论】:

以上是关于swift 如何一次删除多个 PHAsset的主要内容,如果未能解决你的问题,请参考以下文章

如何创建 OTP 验证屏幕并在多个 uitextfield 上向后检测删除是 Swift

如何一次从CloudFormation中删除多个全局二级索引?

如何一次删除多个核心数据对象?

Swift和Spritekit sceneDidLoad被调用多个

swift Swift - CloudKit - 添加保存删除多个记录

如何在 AWK 中一次删除多个列和字段分隔符?