我为我的应用程序创建了一个PHAssetCollection来存放我的照片,它运行得很好。但是,我正在尝试使用它,以便用户在按下按钮时可以删除PHAssetCollection。如何删除我在以下代码中创建的整个AssetCollection ("App文件夹“)?
创建PHAssetCollection的代码:
let albumName = "App Folder"
//Check if the folder exists, if not, create it
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let first_Obj:AnyObject = collection.firstObject{
//found the album
self.albumFound = true
self.assetCollection = first_Obj as! PHAssetCollection
}else{
//Album placeholder for the asset collection, used to reference collection in completion handler
var albumPlaceholder:PHObjectPlaceholder!
//create the folder
NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
albumPlaceholder = request.placeholderForCreatedAssetCollection
},
completionHandler: {(success:Bool, error:NSError!)in
if(success){
println("Successfully created folder")
self.albumFound = true
if let collection = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([albumPlaceholder.localIdentifier], options: nil){
self.assetCollection = collection.firstObject as! PHAssetCollection
}
}else{
println("Error creating folder")
self.albumFound = false
}
})
}发布于 2015-07-12 23:05:42
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
PHAssetCollectionChangeRequest.deleteAssetCollections([self.deleteTarget])
}, completionHandler: nil)发布于 2015-07-12 22:04:22
PHAssetCollectionChangeRequest中有一个名为deleteAssetCollections:的类方法,它就是这样做的:请求删除特定的资产集合。看一下文档,您似乎可以用一个PHAssetCollections数组来调用它,如下所示:
PHAssetCollectionChangeRequest.deleteAssetCollections(self.assetCollection)发布于 2019-10-23 05:52:27
只是让它更容易使用。希望这会有所帮助:这里的功能是以编程方式删除自定义相册,并进行错误处理。
func deleteAlbum(albumName: String){
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "title = %@", albumName)
let album = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: options)
// check if album is available
if album.firstObject != nil {
// request to delete album
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.deleteAssetCollections(album)
}, completionHandler: { (success, error) in
if success {
print(" \(albumName) removed succesfully")
} else if error != nil {
print("request failed. please try again")
}
})
}else{
print("requested album \(albumName) not found in photos")
}
}如何使用-
deleteAlbum(albumName: "YourAlbumName")https://stackoverflow.com/questions/31371563
复制相似问题