Priyanka Priyanka - 1 year ago 1198
iOS Question

iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?

Im trying to get the image name using

. But I couldn't find metadata for filename or any method to get the image name. Is there a different way to get the file name?

Answer Source

If you want to get the image name (for example name of last photo in Photos) like IMG_XXX.JPG, you can try this:

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) {
    // get 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]
                      resultHandler:^(NSData *imageData, NSString *dataUTI,
                                      UIImageOrientation orientation, 
                                      NSDictionary *info) 
          NSLog(@"info = %@", info);
          if ([info objectForKey:@"PHImageFileURLKey"]) {
               // path looks like this - 
               // file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
               NSURL *path = [info objectForKey:@"PHImageFileURLKey"];

Hope it helps.

In Swift the code will look like this

PHImageManager.defaultManager().requestImageDataForAsset(asset, options: PHImageRequestOptions(), resultHandler:
    (imagedata, dataUTI, orientation, info) in
    if info!.keys.contains(NSString(string: "PHImageFileURLKey"))
        let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL