Get file size of PHAsset without loading in the resource?

放肆的年华 提交于 2020-02-18 19:57:11

问题


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.


回答1:


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))
 }



回答2:


A safer solution:

[asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
    NSNumber *fileSize = nil;
    NSError *error = nil;
    [contentEditingInput.fullSizeImageURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&error];
    NSLog(@"file size: %@\nerror: %@", fileSize, error);
}];

Swift version:

asset.requestContentEditingInput(with: nil) { (contentEditingInput, _) in
    do {
        let fileSize = try contentEditingInput?.fullSizeImageURL?.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).fileSize
        print("file size: \(String(describing: fileSize))")
    } catch let error {
        fatalError("error: \(error)")
    }
}

Inspired by How to get an ALAsset URL from a PHAsset?



来源:https://stackoverflow.com/questions/45110720/get-file-size-of-phasset-without-loading-in-the-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!