iosobjective-cphotolibrary

PhAsset get fileSize iOS


Is there any way to get a file size from PHAsset object apart from the below API

 - (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset options:(nullable PHImageRequestOptions *)options resultHandler:(void(^)(NSData *__nullable imageData, NSString *__nullable dataUTI, UIImageOrientation orientation, NSDictionary *__nullable info))resultHandler;

We could get the fileSize directy in ALAsset object but i couldnt find it in PHAsset object.

Thanks in advance.


Solution

  • Unfortunately PHAsset doesn't contain such info. Also please note that ALAsset's fileSize doesn't work properly if image is in the cloud. So if you need a stable way of fetching image size from both cloud and local storage just use this:

    // Fetch image data to retrieve file size and path
    PHImageRequestOptions * options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    
    options.synchronous = YES; //Set this to NO if is needed
    
    [[PHImageManager defaultManager] requestImageDataForAsset:photoAsset
                                                      options:options
                                                resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info)
     {
         //(CGFloat)imageData.length returns size in bytes
         NSLog(@"%@",[NSString stringWithFormat:@"%.2lf MB", ((CGFloat)imageData.length)/1024/1024]);
     }];
    

    To gain a little performance set options.sunchronous = NO;.
    But if you need more performance You can try making an ALAsset object from PHAsset and get fileSize from there, but keep in mind that ALAssetLibrary is deprecated and getting file size of image from cloud will not properly work.