iosobjective-calassetslibrary

Replacing ALAssertLibrary to get the filename


Im using the following code to access filename of the image that I gotta upload. I need both filename alongside the file path and size.

  ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
    {
        ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
        NSLog(@"[imageRep filename] : %@", [imageRep filename]);
        [_imageNameArray addObject:[imageRep filename]];
    };

    [_uploadTbleView reloadData];
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];

The problem that Im facing is,

  1. Xcode throws a warning message that ALAssetsLibraryAssetForURLResultBlock is deprecated. How can I replace the above code to get the filename ?
  2. I tried using PHAsset but every time when Im selecting the file, it has got the same file name called asset.jpg for all image files.

Solution

  • 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]
                 requestImageDataForAsset:asset
                                options:imageRequestOptions
                          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"];
         }                                            
        }];
    }