Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file size of PHAsset?

Suppose there is a PHAsset representing image. How to get file size of the image?

The only way I see is using valueForKey: with private ALAssetURL key, and retrieving size of ALAssetRepresentation, but apple can reject such app.

like image 607
kelin Avatar asked Dec 14 '22 10:12

kelin


1 Answers

Swift 4/5 solution

Extension

extension PHAsset {
    var fileSize: Float {
        get {
            let resource = PHAssetResource.assetResources(for: self)
            let imageSizeByte = resource.first?.value(forKey: "fileSize") as! Float
            let imageSizeMB = imageSizeByte / (1024.0*1024.0)
            return imageSizeMB
        }
    }
}

Function

func getImageFileSize(from asset: PHAsset) -> Float{
    let resource = PHAssetResource.assetResources(for: asset)
    let imageSizeByte = resource.first?.value(forKey: "fileSize") as! Float
    let imageSizeMB = imageSizeByte / (1024.0*1024.0)
    return imageSizeMB
}
like image 164
Mamad Farrahi Avatar answered Dec 26 '22 03:12

Mamad Farrahi