Is there a way I can delete an image that is loaded into my app from a UIImagePickerController
?
I want to be able to delete the image from the user's photo library when the user performs a specific action.
I am prompting the user to choose a image from their library, then it gets loaded into my app at which point the app does some shnazzy animation, then actually deletes the image.
Please help!
Yes we can delete a photo. We can use PHAssetChangeRequest
for this operation.
From Apple:
A request to create, delete, change metadata for, or edit the content of a Photos asset, for use in a photo library change block.
class func deleteAssets(_ assets: NSFastEnumeration)
where assets:
An array of PHAsset objects to be deleted.
PHAssetChangeRequest.deleteAssets([assetToDelete])
So, you could use the above code to delete assets.
below is swift 3 code,
PHPhotoLibrary.shared().performChanges({
let imageAssetToDelete = PHAsset.fetchAssets(withALAssetURLs: imageUrls as! [URL], options: nil)
PHAssetChangeRequest.deleteAssets(imageAssetToDelete)
}, completionHandler: {success, error in
print(success ? "Success" : error )
})
Apple doesn't actually allow you to delete from the photo library through an API. The user has to actually go to the Photos app and delete it manually themselves. Apple does allow you write to the photo library:
To save a still image to the user’s
Saved Photos album, use the
UIImageWriteToSavedPhotosAlbum
function. To save a movie to the
user’s Saved Photos album, use the
UISaveVideoAtPathToSavedPhotosAlbum
function.
But for deleting and editing/overriding an existing photo, Apple doesn't have anything like that right now.
Actually, you can delete photos saved by your app (saved to photo library with UIImageWriteToSavedPhotosAlbum API call).
The documented API [ALAsset setImageData:metadata:completionBlock:]
works.
1). Add an image "photo.jpg" to your project
2). Save an image to asset library:
ALAssetsLibrary *lib = [ALAssetsLibrary new];
UIImage *image = [UIImage imageNamed:@"photo.jpg"];
[lib writeImageToSavedPhotosAlbum:image.CGImage metadata:@{} completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(@"Write image %@ to asset library. (Error %@)", assetURL, error);
}];
3). Go to default gallery, you will find photo.jpg in your "Saved Photos" album.
4). Delete this image from asset library:
ALAssetsLibrary *lib = [ALAssetsLibrary new];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
if(asset.isEditable) {
[asset setImageData:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(@"Asset url %@ should be deleted. (Error %@)", assetURL, error);
}];
}
}];
} failureBlock:^(NSError *error) {
}];
5). Go to default gallery, you will find photo.jpg has already been deleted.