Objective-C: how to write to the iOS photo album and get the name of the written file

Using UIImagePickerController it is easy to take a picture in your iOS app. The picture is not immediately saved in the photo library. You must apply UIImageWriteToSavedPhotosAlbum method to write it there. In some situations you need to know the name of the file that the photo library assigns to the image. For example you have an option in your app also to select an image from the photo library. And you want to avoid that the user picks the same photo. So, how to know the name of the file that photo library assigns to the photo? There is a delegate method imagePickerController:didFinishPickingMediaWithInfo:. We make a use of it:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    PHAsset *asset = nil;
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
    if (fetchResult != nil && fetchResult.count > 0) {
        // we sorted the photos by creation date and get the last photo from Photos
        asset = [fetchResult lastObject];
    }
    
    if (asset) {
        // get photo info from this asset
        PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
        imageRequestOptions.synchronous = YES;
        [[PHImageManager defaultManager]
         requestImageDataForAsset:asset
         options:imageRequestOptions
         resultHandler:^(NSData *imageData, NSString *dataUTI,
                         UIImageOrientation orientation,
                         NSDictionary *info)
         {
             
             if ([info objectForKey:@"PHImageFileURLKey"]) {
                 // path looks like this -
                 // file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
                 NSURL *path = [info objectForKey:@"PHImageFileURLKey"];
                 if(path) {
                     NSString *filePath = [[LPPathUtilities applicationDocumentsFolderPath] stringByAppendingPathComponent:[path lastPathComponent]];
                     
                     NSData *dataFromImage = [NSData dataWithData:UIImageJPEGRepresentation(image, 10.0)];
                     if(![dataFromImage writeToFile:filePath atomically:YES]) {
                         // TODO: handle error
                     }
                 }
             }
         }];
    }
}

Unfortunately, the key PHImageFileURLKey is not specified in the Apple documentation. So, there is of course a danger, that this can key can change in the future. But I could not find so far a more easy approach how to get the file name. If you have a better idea, let me know 😉