有关在Swift中删除ios照片资产的问题

有关在Swift中删除ios照片资产的问题,ios,swift,xcode,photo,Ios,Swift,Xcode,Photo,此源代码是一个照片应用程序,类似于iPhone的照片应用程序。 启动应用程序时,将显示每个资产集合视图单元格 我想问的是选择和删除图像资产的能力。如果您查看iPhone照片应用程序,您可以按选择按钮选择照片并删除和共享所选照片。您可以选择任意多张照片,而不仅仅是一张。我已经实现了@iAction SelectButton按下 class PhotoCollectionViewController: UICollectionViewController { @IBOutlet weak

此源代码是一个照片应用程序,类似于iPhone的照片应用程序。 启动应用程序时,将显示每个
资产
集合视图单元格

我想问的是选择和删除图像资产的能力。如果您查看iPhone照片应用程序,您可以按选择按钮选择照片并删除和共享所选照片。您可以选择任意多张照片,而不仅仅是一张。我已经实现了
@iAction SelectButton按下

class PhotoCollectionViewController: UICollectionViewController {

    @IBOutlet weak var sortButton: UIBarButtonItem!
    @IBOutlet weak var selectButton: UIBarButtonItem!
    @IBOutlet weak var actionButton: UIBarButtonItem!
    @IBOutlet weak var trashButton: UIBarButtonItem!

    // MARK:- Properties
    var fetchResult: PHFetchResult<PHAsset>? {
        didSet {
            OperationQueue.main.addOperation {
                self.collectionView?.reloadSections(IndexSet(0...0))
            }
        }
    }
    var assetCollection: PHAssetCollection?

    // MARK:- Privates
    private let cellReuseIdentifier: String = "photoCell"
    private lazy var cachingImageManager: PHCachingImageManager = {
        return PHCachingImageManager()
    }()

    // MARK:- Life Cycle
    deinit {
        PHPhotoLibrary.shared().unregisterChangeObserver(self)
    }

    @IBAction func sortButtonPressed(_ sender: UIBarButtonItem) {

        let fetchOptions: PHFetchOptions = PHFetchOptions()

        if (self.sortButton.title == "In the past") {
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
                                                             ascending: false)]
            self.fetchResult = PHAsset.fetchAssets(in: assetCollection!, options: fetchOptions )
            self.sortButton.title = "The latest"
        } else if (self.sortButton.title == "The latest") {
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                             ascending: true)]
            self.fetchResult = PHAsset.fetchAssets(in: assetCollection!, options: fetchOptions )
            self.sortButton.title = "In the past"
        }
    }

     @IBAction func seletButtonPressed(_ sender: Any) {
        if (self.sortButton.isEnabled == true) {
            self.sortButton.isEnabled = false
            self.actionButton.isEnabled = true
            self.trashButton.isEnabled = true
        } else if (self.sortButton.isEnabled == false) {
            self.sortButton.isEnabled = true
            self.actionButton.isEnabled = false
            self.trashButton.isEnabled = false
        }

        PHPhotoLibrary.shared().performChanges({
            //Delete Photo
            PHAssetChangeRequest.deleteAssets(self.fetchResult!)
            },
            completionHandler: {(success, error)in
                NSLog("\nDeleted Image -> %@", (success ? "Success":"Error!"))
                if(success){
                }else{
                print("Error: \(error)")
                }
        })
    }
}

extension PhotoCollectionViewController {

    private func configureCell(_ cell: PhotoCollectionViewCell,
                               collectionView: UICollectionView,
                               indexPath: IndexPath) {

        guard let asset: PHAsset = self.fetchResult?.object(at: indexPath.item) else { return }

        let manager: PHCachingImageManager = self.cachingImageManager
        let handler: (UIImage?, [AnyHashable:Any]?) -> Void = { image, _ in

            let cellAtIndex: UICollectionViewCell? = collectionView.cellForItem(at: indexPath)

            guard let cell: PhotoCollectionViewCell = cellAtIndex as? PhotoCollectionViewCell
                else { return }

            cell.imageView.image = image
        }

        manager.requestImage(for: asset,
                             targetSize: CGSize(width: 100, height: 100),
                             contentMode: PHImageContentMode.aspectFill,
                             options: nil,
                             resultHandler: handler)
    }
}

// MARK:- UICollectionViewDataSource
extension PhotoCollectionViewController {

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {

        return self.fetchResult?.count ?? 0
    }
}

extension PhotoCollectionViewController {

    override func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell: PhotoCollectionViewCell
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellReuseIdentifier,
                                                  for: indexPath) as! PhotoCollectionViewCell

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView,
                                 willDisplay cell: UICollectionViewCell,
                                 forItemAt indexPath: IndexPath) {

        guard let cell: PhotoCollectionViewCell = cell as? PhotoCollectionViewCell else {
            return
        }

        self.configureCell(cell, collectionView: collectionView, indexPath: indexPath)
    }
}

// MARK:- UICollectionViewDelegateFlowLayout
extension PhotoCollectionViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {

        guard let flowLayout: UICollectionViewFlowLayout =
            self.collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize.zero}

        let numberOfCellsInRow: CGFloat = 4
        let viewSize: CGSize = self.view.frame.size
        let sectionInset: UIEdgeInsets = flowLayout.sectionInset

        let interitemSpace: CGFloat = flowLayout.minimumInteritemSpacing * (numberOfCellsInRow - 1)

        var itemWidth: CGFloat
        itemWidth = viewSize.width - sectionInset.left - sectionInset.right - interitemSpace
        itemWidth /= numberOfCellsInRow

        let itemSize = CGSize(width: itemWidth, height: itemWidth)

        return itemSize
    }
}

extension PhotoCollectionViewController {
    private func updateCollectionView(with changes: PHFetchResultChangeDetails<PHAsset>) {
        guard let collectionView = self.collectionView else { return }

        // 업데이트는 삭제, 삽입, 다시 불러오기, 이동 순으로 진행합니다
        if let removed: IndexSet = changes.removedIndexes, removed.count > 0 {
            collectionView.deleteItems(at: removed.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        if let inserted: IndexSet = changes.insertedIndexes, inserted.count > 0 {
            collectionView.insertItems(at: inserted.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        if let changed: IndexSet = changes.changedIndexes, changed.count > 0 {
            collectionView.reloadItems(at: changed.map({
                IndexPath(item: $0, section: 0)
            }))
        }

        changes.enumerateMoves { fromIndex, toIndex in
            collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0),
                                    to: IndexPath(item: toIndex, section: 0))
        }
    }
}

// MARK:- PHPhotoLibraryChangeObserver
extension PhotoCollectionViewController: PHPhotoLibraryChangeObserver {

    private func resetCachedAssets() {
        self.cachingImageManager.stopCachingImagesForAllAssets()
    }

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        guard let fetchResult: PHFetchResult<PHAsset> = self.fetchResult
            else { return }

        guard let changes: PHFetchResultChangeDetails<PHAsset> =
            changeInstance.changeDetails(for: fetchResult)
            else { return }

        DispatchQueue.main.sync {
            self.resetCachedAssets()
            self.fetchResult = changes.fetchResultAfterChanges

            if changes.hasIncrementalChanges {
                self.updateCollectionView(with: changes)
            } else {
                self.collectionView?.reloadSections(IndexSet(0...0))
            }
        }
    }
}

extension PhotoCollectionViewController {

    // MARK:- Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        PHPhotoLibrary.shared().register(self)

        self.sortButton.title = "In the past"
        self.actionButton.isEnabled = false
        self.trashButton.isEnabled = false
    }
}

class PhotoCollectionViewController:UICollectionViewController{
@IBVAR排序按钮:UIBAButtonim!
@iBButtonItem!
@iBButtonItem!
@IBVAR垃圾按钮:UIBAButtonim!
//标记:-属性
var fetchResult:PHFetchResult{
迪塞特{
OperationQueue.main.addOperation{
self.collectionView?.reloadSections(索引集(0…0))
}
}
}
var资产收集:PhaseSetCollection?
//马克:士兵
private let cellReuseIdentifier:String=“photoCell”
私有惰性变量cachingImageManager:PHCachingImageManager={
返回PHCachingImageManager()
}()
//马克:生命周期
脱硝{
PHPhotoLibrary.shared().unregisterChangeObserver(自)
}
@iAction func sortButtonPressed(uu发送方:UIBarButtonItem){
让fetchOptions:PHFetchOptions=PHFetchOptions()
if(self.sortButton.title==“过去”){
fetchOptions.sortDescriptors=[NSSortDescriptor(键:“modificationDate”,
(错误)]
self.fetchResult=PHAsset.fetchAssets(在:assetCollection!中,选项:fetchOptions)
self.sortButton.title=“最新”
}else if(self.sortButton.title==“最新的”){
fetchOptions.sortDescriptors=[NSSortDescriptor(键:“creationDate”,
(正确)]
self.fetchResult=PHAsset.fetchAssets(在:assetCollection!中,选项:fetchOptions)
self.sortButton.title=“过去”
}
}
@iAction func SeletButton已按下(\发送方:任意){
if(self.sortButton.isEnabled==true){
self.sortButton.isEnabled=false
self.actionButton.isEnabled=true
self.trashButton.isEnabled=true
}else if(self.sortButton.isEnabled==false){
self.sortButton.isEnabled=true
self.actionButton.isEnabled=false
self.trashButton.isEnabled=false
}
PHPhotoLibrary.shared().performChanges({
//删除照片
PHAssetChangeRequest.deleteAssets(self.fetchResult!)
},
completionHandler:{(成功,错误)在
NSLog(“\n删除的图像->%@”,(成功?:“错误!”)
如果(成功){
}否则{
打印(“错误:\(错误)”)
}
})
}
}
扩展光电收集控制器{
专用功能配置单元(uCell:PhotoCollectionViewCell,
collectionView:UICollectionView,
indepath:indepath){
保护let资产:PHAsset=self.fetchResult?.object(位于:indexPath.item)else{return}
let manager:PHCachingImageManager=self.cachingImageManager
let handler:(UIImage?,[AnyHashable:Any]?)->Void={image,uin
让cellAtIndex:UICollectionViewCell?=collectionView.cellForItem(位于:indexPath)
保护let单元:PhotoCollectionViewCell=单元索引为?PhotoCollectionViewCell
else{return}
cell.imageView.image=图像
}
manager.requestImage(用于:资产、,
targetSize:CGSize(宽:100,高:100),
contentMode:PHImageContentMode.aspectFill,
选项:无,
resultHandler:处理程序)
}
}
//标记:-UICollectionViewDataSource
扩展光电收集控制器{
重写func numberOfSections(在collectionView:UICollectionView中)->Int{
返回1
}
重写func collectionView(collectionView:UICollectionView,
NumberOfItemsSection:Int)->Int{
返回self.fetchResult?计数0
}
}
扩展光电收集控制器{
重写func collectionView(collectionView:UICollectionView,
cellForItemAt indexPath:indexPath)->UICollectionViewCell{
let电池:光收集电池
cell=collectionView.DequeueReuseAbleCell(带ReuseIdentifier:self.cellReuseIdentifier,
for:indexath)as!PhotoCollectionViewCell
返回单元
}
重写func collectionView(collectionView:UICollectionView,
将显示单元格:UICollectionViewCell,
forItemAt indexPath:indexPath){
保护let单元:PhotoCollectionViewCell=单元为?PhotoCollectionViewCell-else{
返回
}
configureCell(单元格,collectionView:collectionView,indexPath:indexPath)
}
}
//标记:-UICollectionViewDelegateFlowLayout
扩展PhotoCollectionViewController:UICollectionViewDelegateFlowLayout{
func collectionView(collectionView:UICollectionView,
布局集合视图布局:UICollectionViewLayout,
sizeForItemAt indexPath:indexPath)->CGSize{
guard let flowLayout:UICollectionViewFlowLayout=
self.collectionViewLayout作为?UICollectionViewFlowLayout else{return CGSize.zero}
设NumberOfCellsRow:CGFloat=4
让
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    //Delete Photo
    PHAssetChangeRequest.deleteAssets(delShotsAsset)
    },
    completionHandler: {(success, error)in
        NSLog("\nDeleted Image -> %@", (success ? "Success":"Error!"))
        if(success){

        }else{
            println("Error: \(error)")
        }
})