Search code examples
iosobjective-ciphoneuiimagepickercontroller

How to delete an image from photo library using UIImagePickerController


I am using UIImagePickerController in my application to pick up the image. I need to delete this image synchronously from iOS PhotoLibrary after picking it up in my application.

- (BOOL)createAndInsertNewElementFromDictionary:(NSDictionary*)dict
{
AlbumElement *newElement;

if ([dict[UIImagePickerControllerMediaType]
     isEqualToString:(NSString*)kUTTypeMovie])
{
    NSURL *mediaUrl = dict[UIImagePickerControllerMediaURL];
    newElement = [AlbumElement createElementWithMediaUrl:mediaUrl
                                                 inAlbum:_album.name];

}
else if ([dict[UIImagePickerControllerMediaType]
          isEqualToString:(NSString*)kUTTypeImage])
{
    UIImage *image = [dict[UIImagePickerControllerOriginalImage] copy];
    newElement = [AlbumElement createElementWithImage:image
                                              inAlbum:_album.name];
}

if (newElement != nil)
{
    [_album.elements insertObject:newElement atIndex:0];

    UIImage *icon = [UIImage imageWithContentsOfFile:[newElement iconFullPath]];
    [AlbumElement writeImageToFileWithImage:icon
                                 atFullPath:_album.albumIconPath];
}
else
{
    NSLog(@"Element was NOT added!");
    return NO;
}

return YES;
}

Solution

  • NSURL *url = [dict objectForKey:@"UIImagePickerControllerReferenceURL"] ;  
    
    PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
     [library performChanges:^{
    // Here assetsURLs is array of url's you want to delete 
        PHFetchResult *assetsToBeDeleted = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:url] options:nil];
        [PHAssetChangeRequest deleteAssets:assetsToBeDeleted];
    } completionHandler:^(BOOL success, NSError *error)
     {
         // Check error and success here
    }];