Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file size of PHAsset without loading in the resource?

Is there a way to get the file size on disk of a PHAsset without doing requestImageDataForAsset or converting it to ALAsset? I am loading in previews of a user's photo library - potentially many thousands of them - and it's imperative to my app that they know the size before import.

like image 339
Ryan Daulton Avatar asked Jul 14 '17 19:07

Ryan Daulton


1 Answers

You can grab the fileSize of a PHAsset and convert it to human readable form like this:

      let resources = PHAssetResource.assetResources(for: yourAsset) // your PHAsset

      var sizeOnDisk: Int64? = 0

      if let resource = resources.first {
        let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong
        sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64!))
      }

Then use your sizeOnDisk variable and pass it into a method like this...

func converByteToHumanReadable(_ bytes:Int64) -> String {
     let formatter:ByteCountFormatter = ByteCountFormatter()
     formatter.countStyle = .binary

     return formatter.string(fromByteCount: Int64(bytes))
 }
like image 158
Ryan Daulton Avatar answered Oct 14 '22 03:10

Ryan Daulton